From a496a864feb525723e06d3a03e8e554698d1302a Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 06:02:20 +0000 Subject: [PATCH 01/13] feat(test): mount conventional providers in the agent-bundle/test harness The public harness (renderRoute, renderRouteEvents, invokeCli, in-memory MCP) now discovers and executes src/providers/* for every manifest-backed request scope exactly like the generated entries: same deterministic key order, same surface-specific invocation, same fail-closed messages, seeded processLifetime. context.providers still wins when passed. The execution contract the codegen emits and the harness runs now lives in one module and is pinned together. Refs #313, #366. --- .../test-harness-conventional-providers.md | 5 + docs/entry-conventions.md | 5 +- packages/agent-bundle/README.md | 23 +++ .../route-harness/src/cli/tooling/inspect.ts | 24 +++ .../route-harness/src/cli/tooling/report.tsx | 24 +++ .../src/mcp/harness/tools/tooling.tsx | 28 ++++ .../src/providers/library-tooling.ts | 25 ++++ .../src/scripts/tooling-summary.tsx | 26 ++++ .../agent-bundle/src/build/entry-shell.ts | 11 +- .../src/routes/provider-execution.ts | 95 ++++++++++++ packages/agent-bundle/src/rstest/index.ts | 1 + .../agent-bundle/src/rstest/setup-module.ts | 5 + packages/agent-bundle/src/test/cli.ts | 10 ++ packages/agent-bundle/src/test/index.ts | 3 +- packages/agent-bundle/src/test/manifest.ts | 35 +++++ packages/agent-bundle/src/test/mcp.ts | 12 ++ packages/agent-bundle/src/test/providers.ts | 84 +++++++++++ packages/agent-bundle/src/test/registry.ts | 14 ++ packages/agent-bundle/src/test/render.ts | 32 +++- .../agent-bundle/tests/entry-shell.test.ts | 84 +++++++++++ .../tests/projection/cli-dispatch.test.ts | 3 + .../tests/projection/mcp-in-memory.test.ts | 3 +- .../tests/projection/providers.test.ts | 137 ++++++++++++++++++ .../tests/support/contract-matrix-fixtures.ts | 1 + .../tests/test-harness-manifest.test.ts | 39 +++++ 25 files changed, 714 insertions(+), 15 deletions(-) create mode 100644 .changeset/test-harness-conventional-providers.md create mode 100644 packages/agent-bundle/fixtures/route-harness/src/cli/tooling/inspect.ts create mode 100644 packages/agent-bundle/fixtures/route-harness/src/cli/tooling/report.tsx create mode 100644 packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx create mode 100644 packages/agent-bundle/fixtures/route-harness/src/providers/library-tooling.ts create mode 100644 packages/agent-bundle/fixtures/route-harness/src/scripts/tooling-summary.tsx create mode 100644 packages/agent-bundle/src/routes/provider-execution.ts create mode 100644 packages/agent-bundle/src/test/providers.ts create mode 100644 packages/agent-bundle/tests/projection/providers.test.ts diff --git a/.changeset/test-harness-conventional-providers.md b/.changeset/test-harness-conventional-providers.md new file mode 100644 index 000000000..c4a50820f --- /dev/null +++ b/.changeset/test-harness-conventional-providers.md @@ -0,0 +1,5 @@ +--- +"agent-bundle": patch +--- + +The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity. Passing `context.providers` opts out and mounts the explicit map verbatim. The test manifest gains `providers`, the generated Rstest setup registers provider loaders, and the provider execution contract shared by the generated scopes and the harness lives in one module. diff --git a/docs/entry-conventions.md b/docs/entry-conventions.md index 006154c55..d3a5b2d5e 100644 --- a/docs/entry-conventions.md +++ b/docs/entry-conventions.md @@ -172,7 +172,10 @@ expected degradation should return an honest unavailable-shaped value instead of throwing. `invocation.kind` stays surface-specific (`tool`, `event`, `cli`, `script`), so a provider can branch on the entry surface deliberately. `processLifetime` is reserved for the framework-owned process identity and hit -counter, so provider filenames must not derive that key. +counter, so provider filenames must not derive that key. The `agent-bundle/test` +harness mounts the same providers, in the same order and with the same +fail-closed semantics, for every manifest-backed helper; a test passes +`context.providers` to substitute an explicit map instead. Route-unit and CLI-dispatch tests inject provider values through the same `context` seam as identity axes (`renderRoute(id, { context: { providers: diff --git a/packages/agent-bundle/README.md b/packages/agent-bundle/README.md index b46f56646..7ea825c27 100644 --- a/packages/agent-bundle/README.md +++ b/packages/agent-bundle/README.md @@ -411,6 +411,29 @@ than paying for a build per route. Every failure — an unknown route, a refused route kind, a rejected input, a render error — names the route id, the target kind, and the module provenance. +Conventional request context providers (`src/providers/*`, see +[entry conventions](../../docs/entry-conventions.md#request-context-providers-power-tier)) +are mounted automatically for every manifest-backed helper — `renderRoute`, +`renderRouteEvents`, `invokeCli`, and the in-memory MCP helpers — exactly as the +generated request scopes mount them: discovered from the compiled manifest, +executed once per request in the same deterministic key order, handed the same +surface-specific `invocation` (`tool`, `event`, `cli`, `script`), and failing the +request closed when a factory throws. `providers.processLifetime` carries the +test worker's process identity and a per-request hit counter, like the +artifact's. Pass `context.providers` to opt out: an explicit map is mounted +verbatim and no conventional provider runs, which is how a test stubs a provider +that would otherwise reach the network or the file system. + +```ts +// Real providers, as the artifact would mount them. +const real = await renderRoute('tool:library/summarize', { input: { title: 'Dune' } }); + +// Stubbed providers: nothing under src/providers/ executes. +const stubbed = await invokeCli(['library', 'audit', './books'], { + context: { providers: { libraryTooling: { tool: 'ffprobe 6.1' } } }, +}); +``` + Matchers over the Agent Document contracts: `toHaveStatus`, `toContainMarkdown`, `toContainText`, `toHaveValue`, `toHaveError`, and `toHaveNodeKinds`. diff --git a/packages/agent-bundle/fixtures/route-harness/src/cli/tooling/inspect.ts b/packages/agent-bundle/fixtures/route-harness/src/cli/tooling/inspect.ts new file mode 100644 index 000000000..7d509a2e1 --- /dev/null +++ b/packages/agent-bundle/fixtures/route-harness/src/cli/tooling/inspect.ts @@ -0,0 +1,24 @@ +import { agent } from '@agent-bundle/runtime'; +import type { CliRouteConfig, CliRouteProps } from 'agent-bundle'; +import { z } from 'zod'; + +export const config = { + description: 'Reports the request providers a plain command observes.', +} satisfies CliRouteConfig; + +export const inputSchema = z.object({}).strict(); + +export const resultSchema = z.object({ + keys: z.array(z.string()), + libraryTooling: z.unknown().optional(), + processLifetime: z.object({ hits: z.number().int().min(1), instanceId: z.string(), pid: z.number().int() }).strict(), +}).strict(); + +export default async function inspect(_props: CliRouteProps) { + const { providers } = await agent(); + return { + keys: Object.keys(providers).sort(), + libraryTooling: providers['libraryTooling'], + processLifetime: providers['processLifetime'], + }; +} diff --git a/packages/agent-bundle/fixtures/route-harness/src/cli/tooling/report.tsx b/packages/agent-bundle/fixtures/route-harness/src/cli/tooling/report.tsx new file mode 100644 index 000000000..13b43e542 --- /dev/null +++ b/packages/agent-bundle/fixtures/route-harness/src/cli/tooling/report.tsx @@ -0,0 +1,24 @@ +import { Agent, agent, type JsonValue } from '@agent-bundle/runtime'; +import type { CliRouteConfig, CliRouteProps } from 'agent-bundle'; +import { z } from 'zod'; + +export const config = { + description: 'Renders the request providers a rendered command observes.', +} satisfies CliRouteConfig; + +export const inputSchema = z.object({}).strict(); + +export const resultSchema = z.object({ + keys: z.array(z.string()), + libraryTooling: z.unknown().optional(), +}).strict(); + +export default async function ToolingReport(_props: CliRouteProps) { + const { providers } = await agent(); + const value = { keys: Object.keys(providers).sort(), libraryTooling: providers['libraryTooling'] as JsonValue }; + return ( + + {`tooling: ${JSON.stringify(providers['libraryTooling'])}`} + + ); +} diff --git a/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx b/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx new file mode 100644 index 000000000..439aa383c --- /dev/null +++ b/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx @@ -0,0 +1,28 @@ +import { Agent, agent, type JsonValue } from '@agent-bundle/runtime'; +import { z } from 'zod'; + +export const config = { + annotations: { readOnlyHint: true }, + description: 'Reports the request providers an MCP tool observes.', + title: 'Tooling', +}; + +export const inputSchema = z.object({ + /** Makes the `library-tooling` provider throw, to prove the request fails closed. */ + failProvider: z.boolean().optional(), +}).strict(); + +export const resultSchema = z.object({ + keys: z.array(z.string()), + libraryTooling: z.unknown().optional(), +}).strict(); + +export default async function Tooling() { + const { providers } = await agent(); + const value = { keys: Object.keys(providers).sort(), libraryTooling: providers['libraryTooling'] as JsonValue }; + return ( + + {`tooling: ${JSON.stringify(providers['libraryTooling'])}`} + + ); +} diff --git a/packages/agent-bundle/fixtures/route-harness/src/providers/library-tooling.ts b/packages/agent-bundle/fixtures/route-harness/src/providers/library-tooling.ts new file mode 100644 index 000000000..2ea925c5a --- /dev/null +++ b/packages/agent-bundle/fixtures/route-harness/src/providers/library-tooling.ts @@ -0,0 +1,25 @@ +import type { AgentProviderContext } from 'agent-bundle'; + +/** + * A conventional request context provider. The harness mounts it for every + * manifest request scope exactly as the generated entries do, so routes on + * every surface observe `providers.libraryTooling` with the surface-specific + * invocation kind the provider saw. + */ +export default async function libraryTooling({ invocation, signal }: AgentProviderContext) { + if (signal.aborted) throw new DOMException('aborted', 'AbortError'); + const input = invocation.kind === 'tool' ? invocation.props.input : undefined; + if (typeof input === 'object' && input !== null && (input as { readonly failProvider?: unknown }).failProvider === true) { + throw new Error('ffprobe is not installed'); + } + const surface = invocation.kind === 'tool' + ? invocation.props.operationId + : invocation.kind === 'cli' + ? invocation.props.command + : invocation.kind === 'script' + ? invocation.props.name + : invocation.kind === 'event' + ? invocation.props.event + : invocation.props.view; + return { kind: invocation.kind, surface, tool: 'ffprobe 6.1' }; +} diff --git a/packages/agent-bundle/fixtures/route-harness/src/scripts/tooling-summary.tsx b/packages/agent-bundle/fixtures/route-harness/src/scripts/tooling-summary.tsx new file mode 100644 index 000000000..d134b2e42 --- /dev/null +++ b/packages/agent-bundle/fixtures/route-harness/src/scripts/tooling-summary.tsx @@ -0,0 +1,26 @@ +import { Agent, agent, type JsonValue } from '@agent-bundle/runtime'; +import { z } from 'zod'; + +export const resultSchema = z.object({ + arguments: z.number().int().nonnegative(), + keys: z.array(z.string()), + libraryTooling: z.unknown().optional(), +}).strict(); + +export default async function ToolingSummary({ argv, signal }: { + readonly argv: readonly string[]; + readonly signal: AbortSignal; +}) { + if (signal.aborted) throw new DOMException('aborted', 'AbortError'); + const { providers } = await agent(); + const value = { + arguments: argv.length, + keys: Object.keys(providers).sort(), + libraryTooling: providers['libraryTooling'] as JsonValue, + }; + return ( + + {`Summarized ${String(argv.length)} arguments.`} + + ); +} diff --git a/packages/agent-bundle/src/build/entry-shell.ts b/packages/agent-bundle/src/build/entry-shell.ts index 410afb912..ba05e3a73 100644 --- a/packages/agent-bundle/src/build/entry-shell.ts +++ b/packages/agent-bundle/src/build/entry-shell.ts @@ -4,6 +4,7 @@ import { fileURLToPath } from 'node:url'; import { eventIpcRuntimeSpecifier, eventProjectRuntimeSpecifier } from '../adapters/hook-contract.ts'; import { stableJson } from '../core/digest.ts'; import type { NormalizedHook, NormalizedStateDefinition } from '../core/types.ts'; +import { orderedProviders } from '../routes/provider-execution.ts'; import { providerKeyFromName } from '../routes/providers.ts'; import type { CompiledAgentRoute, CompiledCliCommand, CompiledProvider } from '../routes/types.ts'; @@ -560,12 +561,6 @@ const eventRouteRecords = ( ): readonly string[] => routes.map((route, index) => ` ${JSON.stringify(route.id)}: Object.freeze({ event: ${JSON.stringify(route.eventRoute!.event)}, id: ${JSON.stringify(route.id)}, kind: 'event-route', module: route${String(offset + index)}, name: ${JSON.stringify(route.eventRoute!.event)} }),`); -const orderedProviders = (providers: readonly CompiledProvider[]): readonly CompiledProvider[] => - [...providers].sort((left, right) => { - const byKey = providerKeyFromName(left.name).localeCompare(providerKeyFromName(right.name)); - return byKey === 0 ? left.source.localeCompare(right.source) : byKey; - }); - const providerImports = (providers: readonly CompiledProvider[]): readonly string[] => providers.map((provider, index) => `import * as provider${String(index)} from ${JSON.stringify(provider.source)};`); @@ -588,7 +583,9 @@ const processLifetimeValueSource = * (shared Flight worker, rendered CLI/script worker, plain routed CLI): once * per request, sequentially in deterministic key order, fail-closed on a * missing factory or a thrown/rejected factory, with the framework-owned - * `processLifetime` value seeded first. + * `processLifetime` value seeded first. The emitted loop mirrors + * `executeProviders` in `../routes/provider-execution.ts`, which the + * in-process test harness runs; `entry-shell.test.ts` pins the two together. */ const providerExecutionSource = ( providers: readonly CompiledProvider[], diff --git a/packages/agent-bundle/src/routes/provider-execution.ts b/packages/agent-bundle/src/routes/provider-execution.ts new file mode 100644 index 000000000..b43a01ded --- /dev/null +++ b/packages/agent-bundle/src/routes/provider-execution.ts @@ -0,0 +1,95 @@ +import { providerKeyFromName } from './providers.ts'; +import type { CompiledProvider } from './types.ts'; + +/** + * The per-request provider execution contract every generated request scope + * implements (#313, #366): once per request, sequentially in deterministic + * key order, fail-closed on a missing factory or a thrown/rejected factory, + * with the framework-owned `processLifetime` value seeded first. + * + * `entry-shell.ts` emits this loop as generated source so artifacts stay + * self-contained; `agent-bundle/test` runs it in-process through + * {@link executeProviders}. Ordering and the fail-closed messages live here so + * the two cannot drift: the harness must mount exactly what the artifact does. + */ + +/** Deterministic execution order: by mounted key, then by source path for a key collision. */ +export const orderedProviders = >( + providers: readonly T[], +): readonly T[] => [...providers].sort((left, right) => { + const byKey = providerKeyFromName(left.name).localeCompare(providerKeyFromName(right.name)); + return byKey === 0 ? left.source.localeCompare(right.source) : byKey; +}); + +export const providerFactoryMissingMessage = (key: string, source: string): string => + `Context provider "${key}" (${source}) must default-export a factory.`; + +export const providerFailedMessage = (key: string, source: string, cause: unknown): string => + `Context provider "${key}" (${source}) failed: ${cause instanceof Error ? cause.message : String(cause)}`; + +/** The framework-owned process identity a request scope mounts at `providers.processLifetime`. */ +export interface ProviderProcessLifetime { + hits: number; + readonly instanceId: string; + readonly pid: number; +} + +export const createProviderProcessLifetime = (): ProviderProcessLifetime => ({ + hits: 0, + instanceId: crypto.randomUUID(), + pid: process.pid, +}); + +/** The immutable snapshot of one process lifetime a request observes. */ +export const providerProcessLifetimeValue = ( + lifetime: ProviderProcessLifetime, +): { readonly hits: number; readonly instanceId: string; readonly pid: number } => ({ + hits: lifetime.hits, + instanceId: lifetime.instanceId, + pid: lifetime.pid, +}); + +/** One loaded provider module in execution order, with the identity its failures name. */ +export interface ExecutableProvider { + readonly key: string; + readonly module: { readonly default?: unknown }; + /** Project-relative path, as the generated scopes report it. */ + readonly source: string; +} + +export interface ExecuteProvidersOptions { + /** The surface-specific provider invocation (`tool`, `event`, `cli`, `script`). */ + readonly invocation: unknown; + readonly processLifetime: ProviderProcessLifetime; + /** Providers already in {@link orderedProviders} order. */ + readonly providers: readonly ExecutableProvider[]; + readonly signal: AbortSignal; +} + +/** + * Executes conventional providers for one request exactly as a generated + * request scope does. The caller increments `processLifetime.hits` before the + * call, as every generated scope does before its provider loop. + */ +export const executeProviders = async ( + options: ExecuteProvidersOptions, +): Promise>> => { + const values: Record = { + processLifetime: providerProcessLifetimeValue(options.processLifetime), + }; + for (const provider of options.providers) { + const factory = provider.module.default; + if (typeof factory !== 'function') { + throw new TypeError(providerFactoryMissingMessage(provider.key, provider.source)); + } + try { + values[provider.key] = await (factory as (context: { + readonly invocation: unknown; + readonly signal: AbortSignal; + }) => unknown)({ invocation: options.invocation, signal: options.signal }); + } catch (error) { + throw new Error(providerFailedMessage(provider.key, provider.source, error), { cause: error }); + } + } + return values; +}; diff --git a/packages/agent-bundle/src/rstest/index.ts b/packages/agent-bundle/src/rstest/index.ts index 46611b3d6..516ff23f2 100644 --- a/packages/agent-bundle/src/rstest/index.ts +++ b/packages/agent-bundle/src/rstest/index.ts @@ -131,6 +131,7 @@ export const agentBundleRstest = async ( export type { AgentBundleTestManifest, + TestableProviderDescriptor, TestableRouteDescriptor, TestableStateDescriptor, } from '../test/manifest.ts'; diff --git a/packages/agent-bundle/src/rstest/setup-module.ts b/packages/agent-bundle/src/rstest/setup-module.ts index fc68a5dc7..54d6a6da0 100644 --- a/packages/agent-bundle/src/rstest/setup-module.ts +++ b/packages/agent-bundle/src/rstest/setup-module.ts @@ -37,6 +37,8 @@ const specifier = (source: string): string => source.replaceAll('\\', '/'); export const routeTestSetupSource = (manifest: AgentBundleTestManifest): string => { const loaders = renderableRoutes(manifest) .map((route) => ` ${JSON.stringify(route.id)}: () => import(${JSON.stringify(specifier(route.source))}),`); + const providerLoaders = (manifest.providers ?? []) + .map((provider) => ` ${JSON.stringify(provider.id)}: () => import(${JSON.stringify(specifier(provider.source))}),`); return [ '// @generated by agent-bundle/rstest. Do not edit: rerun Rstest to regenerate.', '//', @@ -48,6 +50,9 @@ export const routeTestSetupSource = (manifest: AgentBundleTestManifest): string ...loaders, ' },', ` manifest: JSON.parse(${JSON.stringify(JSON.stringify(manifest))}),`, + ...(providerLoaders.length === 0 + ? [] + : [' providerLoaders: {', ...providerLoaders, ' },']), ...(manifest.state === undefined ? [] : [` stateLoader: () => import(${JSON.stringify(specifier(manifest.state.source))}),`]), diff --git a/packages/agent-bundle/src/test/cli.ts b/packages/agent-bundle/src/test/cli.ts index 7cc616086..39f683c16 100644 --- a/packages/agent-bundle/src/test/cli.ts +++ b/packages/agent-bundle/src/test/cli.ts @@ -24,6 +24,7 @@ import type { CliRenderedEvent } from '../cli-entry.ts'; import type { CompiledCliCommand } from '../routes/types.ts'; import { AgentTestError, captured } from './errors.ts'; import { CLI_DISPATCH_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; +import { mountProviders } from './providers.ts'; import { registeredRouteLoader, testManifest } from './registry.ts'; import { prepareCliRenderHost, type HarnessOptionsArguments, type RenderRouteContextInit } from './render.ts'; import type { AgentRouteModule, RenderedRouteProvenance } from './types.ts'; @@ -228,6 +229,14 @@ export const invokeCli = async ( throw new CliInputError(error instanceof Error ? error.message : String(error)); } const root = process.cwd(); + // Same provider invocation the generated plain-command path builds (#366). + const providers = await mountProviders({ + explicit: context.providers, + invocation: { kind: 'cli', props: { args: execution.args, command: commandPath(command) } }, + manifest, + provenance: { ...provenance, kind: 'cli', routeId: command.routeId, source: 'manifest', targets: [] }, + signal: execution.signal, + }); const result = await runtime.runAgentRequest({ capabilities: { command: runtime.unavailable(), @@ -238,6 +247,7 @@ export const invokeCli = async ( host: runtime.unavailable('unsupported-surface'), workspace: runtime.available({ root }, 'derived'), ...context, + providers, invocation: { kind: 'cli', operationId: command.routeId, diff --git a/packages/agent-bundle/src/test/index.ts b/packages/agent-bundle/src/test/index.ts index d6d94fb30..3d5145f3f 100644 --- a/packages/agent-bundle/src/test/index.ts +++ b/packages/agent-bundle/src/test/index.ts @@ -47,11 +47,12 @@ export type { CompileTestManifestOptions, TestManifestPluginIdentity, TestableAppDescriptor, + TestableProviderDescriptor, TestableRouteDescriptor, TestableStateDescriptor, } from './manifest.ts'; export { AGENT_TEST_REGISTRY_VERSION, registerTestRoutes, testManifest } from './registry.ts'; -export type { AgentTestRouteRegistry } from './registry.ts'; +export type { AgentProviderModuleLoader, AgentTestRouteRegistry } from './registry.ts'; export { AgentTestError } from './errors.ts'; export type { AgentTestErrorCode } from './errors.ts'; export { renderRoute, renderRouteEvents } from './render.ts'; diff --git a/packages/agent-bundle/src/test/manifest.ts b/packages/agent-bundle/src/test/manifest.ts index 0906748cf..b8ca6cda5 100644 --- a/packages/agent-bundle/src/test/manifest.ts +++ b/packages/agent-bundle/src/test/manifest.ts @@ -4,9 +4,12 @@ import type { Diagnostic } from '../core/diagnostics.ts'; import { stableJson } from '../core/digest.ts'; import { deepFreeze } from '../core/freeze.ts'; import type { NormalizedMcpApp, NormalizedStateDefinition } from '../core/types.ts'; +import { orderedProviders } from '../routes/provider-execution.ts'; +import { providerKeyFromName } from '../routes/providers.ts'; import type { CompiledAgentRoute, CompiledCliCommand, + CompiledProvider, CompiledRouteGraph, CompiledRouteKind, } from '../routes/types.ts'; @@ -154,6 +157,21 @@ export interface TestableStateDescriptor { readonly source: string; } +/** + * One conventional `src/providers/.ts` context provider the harness + * mounts for every manifest request scope, exactly as the generated entries + * do (#313). `key` is the camel-cased request-context key. + */ +export interface TestableProviderDescriptor { + readonly id: string; + readonly key: string; + readonly name: string; + /** Project-relative POSIX path of the provider module. */ + readonly relativePath: string; + /** Absolute provider module path. */ + readonly source: string; +} + /** One normalized MCP App declaration addressable by the browser proof level. */ export interface TestableAppDescriptor { readonly _meta?: Readonly>; @@ -201,6 +219,12 @@ export interface AgentBundleTestManifest { readonly projectRoot: string; /** The level the manifest and its registered loaders alone supply; every other level stamps its own. */ readonly proofLevel: AgentTestProofLevel; + /** + * Conventional request context providers, in the execution order every + * generated request scope uses; the harness mounts them automatically unless + * a test passes `context.providers`. Absent when the project declares none. + */ + readonly providers?: readonly TestableProviderDescriptor[]; readonly routes: Readonly>; /** Conventional project state mounted automatically for manifest route renders. */ readonly state?: TestableStateDescriptor; @@ -222,6 +246,16 @@ const descriptorOf = (route: CompiledAgentRoute): TestableRouteDescriptor => ({ source: route.source, }); +const providerDescriptors = ( + providers: readonly CompiledProvider[], +): readonly TestableProviderDescriptor[] => orderedProviders(providers).map((provider) => ({ + id: provider.id, + key: providerKeyFromName(provider.name), + name: provider.name, + relativePath: provider.provenance.relativePath, + source: provider.source, +})); + const graphRoutes = (graph: CompiledRouteGraph): readonly CompiledAgentRoute[] => [ ...(graph.cli?.routes ?? []), ...graph.events, @@ -304,6 +338,7 @@ export const testManifestFromRouteGraph = (input: { plugin: input.plugin ?? FALLBACK_PLUGIN_IDENTITY, projectRoot: input.projectRoot, proofLevel: ROUTE_UNIT_PROOF_LEVEL, + ...(input.graph.providers.length === 0 ? {} : { providers: providerDescriptors(input.graph.providers) }), routes, ...(input.state === undefined ? {} diff --git a/packages/agent-bundle/src/test/mcp.ts b/packages/agent-bundle/src/test/mcp.ts index af03c154b..201c0b056 100644 --- a/packages/agent-bundle/src/test/mcp.ts +++ b/packages/agent-bundle/src/test/mcp.ts @@ -24,6 +24,7 @@ import type { createGeneratedRuntimeState } from '@agent-bundle/runtime/mount'; import { AgentTestError, captured } from './errors.ts'; import { MCP_IN_MEMORY_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; +import { mountProviders } from './providers.ts'; import { registeredRouteLoader, testManifest } from './registry.ts'; import type { HarnessOptionsArguments, RenderRouteContextInit } from './render.ts'; import type { RenderedRouteProvenance, TestableRouteDescriptor } from './types.ts'; @@ -330,6 +331,16 @@ export const openInMemoryMcpServer = async < } const bindings = await runtimeState?.requestBindings({ signal: request.signal }); try { + // Conventional providers run before the scope opens, over the same + // tool invocation the generated Flight worker hands them. + const descriptor = manifest.routes[route.id]; + const providers = await mountProviders({ + explicit: context.providers, + invocation: request.invocation, + manifest, + ...(descriptor === undefined ? {} : { provenance: routeProvenance(descriptor, manifest) }), + signal: request.signal, + }); return streamOf(await dependencies.runAgentRequest({ // Mirror the Flight worker boundary while allowing the documented // harness context seam to override forwarded transport identity. @@ -338,6 +349,7 @@ export const openInMemoryMcpServer = async < session: transport.session, workspace: transport.workspace, ...context, + providers, invocation: { kind: 'tool' as const, operationId: route.id, diff --git a/packages/agent-bundle/src/test/providers.ts b/packages/agent-bundle/src/test/providers.ts new file mode 100644 index 000000000..83be73072 --- /dev/null +++ b/packages/agent-bundle/src/test/providers.ts @@ -0,0 +1,84 @@ +import type { AgentProviderValues } from '@agent-bundle/runtime'; + +import { + createProviderProcessLifetime, + executeProviders, + providerProcessLifetimeValue, + type ExecutableProvider, +} from '../routes/provider-execution.ts'; +import { AgentTestError } from './errors.ts'; +import type { AgentBundleTestManifest, TestableProviderDescriptor } from './manifest.ts'; +import { registeredProviderLoader } from './registry.ts'; +import type { RenderedRouteProvenance } from './types.ts'; + +/** + * Conventional request context providers for harness request scopes. + * + * Every generated request scope discovers `src/providers/*` and executes them + * once per request before `runAgentRequest` (#313, #366). The harness does the + * same for every manifest-backed render, dispatch, and in-memory projection, + * through the shared execution helper the generated scopes mirror, so a test + * observes the provider map the artifact would mount. A test that passes + * `context.providers` opts out: the explicit map is used verbatim, exactly as + * the runtime's request contract reads it. + */ + +/** + * One process identity for this test worker, mirroring the generated scopes' + * module-scope `processLifetime`: `hits` counts every request the harness + * opened in this process, whichever proof level opened it. + */ +const processLifetime = createProviderProcessLifetime(); + +export interface MountProvidersOptions { + /** Explicit provider values from the test; when present they win and nothing is discovered. */ + readonly explicit: AgentProviderValues | undefined; + /** The surface-specific provider invocation the generated scope would pass (`tool`, `event`, `cli`, `script`). */ + readonly invocation: unknown; + /** Absent for a module rendered directly: no project, so nothing to discover. */ + readonly manifest: AgentBundleTestManifest | undefined; + readonly provenance?: RenderedRouteProvenance; + readonly signal: AbortSignal; +} + +const loadProvider = async ( + manifest: AgentBundleTestManifest, + descriptor: TestableProviderDescriptor, + provenance: RenderedRouteProvenance | undefined, +): Promise => { + const loader = registeredProviderLoader(manifest, descriptor.id); + if (loader === undefined) { + throw new AgentTestError( + 'manifest-unavailable', + `Context provider ${descriptor.id} (${descriptor.relativePath}) is compiled but no test-time module loader is registered for it.`, + { + ...(provenance === undefined ? {} : { provenance }), + recovery: 'Build the Rstest configuration with agentBundleRstest() so the generated setup registers provider loaders, or pass context.providers explicitly to skip conventional provider discovery.', + }, + ); + } + return { key: descriptor.key, module: await loader(), source: descriptor.relativePath }; +}; + +/** + * The `providers` value for one harness request scope: the explicit map when + * the test supplied one, otherwise the project's conventional providers + * executed in the generated order over the framework-owned process identity. + */ +export const mountProviders = async (options: MountProvidersOptions): Promise => { + if (options.explicit !== undefined) return options.explicit; + processLifetime.hits += 1; + if (options.manifest === undefined) { + return { processLifetime: providerProcessLifetimeValue(processLifetime) }; + } + const providers: ExecutableProvider[] = []; + for (const descriptor of options.manifest.providers ?? []) { + providers.push(await loadProvider(options.manifest, descriptor, options.provenance)); + } + return executeProviders({ + invocation: options.invocation, + processLifetime, + providers, + signal: options.signal, + }); +}; diff --git a/packages/agent-bundle/src/test/registry.ts b/packages/agent-bundle/src/test/registry.ts index 00886d34a..e7927820a 100644 --- a/packages/agent-bundle/src/test/registry.ts +++ b/packages/agent-bundle/src/test/registry.ts @@ -22,10 +22,14 @@ export type AgentStateModuleLoader = () => Promise<{ readonly default: AgentStateDefinition; }>; +export type AgentProviderModuleLoader = () => Promise<{ readonly default?: unknown }>; + export interface AgentTestRouteRegistry { /** Lazy loaders keyed by compiled route id, so a test only compiles the routes it renders. */ readonly loaders: Readonly>; readonly manifest: AgentBundleTestManifest; + /** Lazy loaders keyed by compiled provider id; present only when the project declares providers. */ + readonly providerLoaders?: Readonly>; readonly stateLoader?: AgentStateModuleLoader; readonly version: number; } @@ -114,6 +118,16 @@ export const registeredStateLoader = ( return registry.stateLoader; }; +/** The provider-module loader generated beside the registered manifest for one compiled provider id. */ +export const registeredProviderLoader = ( + manifest: AgentBundleTestManifest, + providerId: string, +): AgentProviderModuleLoader | undefined => { + const registry = registered(); + if (registry === undefined || !producedRegisteredLoaders(registry, manifest)) return undefined; + return registry.providerLoaders?.[providerId]; +}; + /** The registered manifest's identity, so a loader miss can name the mismatch that caused it. */ export const registeredManifestIdentity = (): { readonly digest: string; readonly projectRoot: string } | undefined => { const registry = registered(); diff --git a/packages/agent-bundle/src/test/render.ts b/packages/agent-bundle/src/test/render.ts index af8dd334e..7100866f0 100644 --- a/packages/agent-bundle/src/test/render.ts +++ b/packages/agent-bundle/src/test/render.ts @@ -29,6 +29,7 @@ import type { import type { CompiledCliCommand } from '../routes/types.ts'; import { AgentTestError, captured } from './errors.ts'; import { ROUTE_UNIT_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; +import { mountProviders } from './providers.ts'; import { registeredManifestIdentity, registeredRouteLoader, @@ -47,7 +48,10 @@ import type { * request contract. `host`, `session`, `actor`, `workspace`, and * `capabilities` are the identity-injection seam for context-dependent route * tests; construct observed values with `available` or `unavailable` from - * `@agent-bundle/runtime`. + * `@agent-bundle/runtime`. `providers` is the opt-out for conventional + * provider discovery: when present it is mounted verbatim; when absent the + * harness executes the project's `src/providers/*` exactly as the generated + * request scopes do. */ export type RenderRouteContext = Omit & { readonly invocation?: Omit; @@ -564,13 +568,14 @@ interface FlightDispatcherOptions { readonly contextProgress?: AgentProgressReporter; readonly limits?: Partial; readonly renderer: Renderer; - readonly requestInit: (request: AgentRenderDispatch) => AgentRequestInit; + /** Async so conventional providers execute inside the request, before the scope opens, as generated scopes do. */ + readonly requestInit: (request: AgentRenderDispatch) => Promise; } const createFlightDispatcher = (options: FlightDispatcherOptions): AgentRuntime.AgentRenderDispatcher => options.renderer.createAgentRenderDispatcher({ execute: async (request) => streamOf(await options.renderer.runAgentRequest({ - ...options.requestInit(request), + ...(await options.requestInit(request)), progress: progressFor(options.collected, options.contextProgress, request.progress), signal: request.signal, }, async () => drain(options.renderer.renderAgentFlight( @@ -667,8 +672,15 @@ export const prepareCliRenderHost = async ( componentProps: (request) => ({ input: parsed, signal: request.signal }), contextProgress: context.progress, renderer, - requestInit: (request) => { + requestInit: async (request) => { const root = process.cwd(); + const providers = await mountProviders({ + explicit: context.providers, + invocation, + manifest: options.manifest, + provenance: { ...options.provenance, routeId: command.routeId }, + signal: request.signal, + }); return { capabilities: { command: renderer.unavailable(), @@ -680,6 +692,7 @@ export const prepareCliRenderHost = async ( workspace: renderer.available({ root }, 'derived'), ...context, ...mounted.context, + providers, invocation: command.mcp === undefined ? { kind: 'cli', @@ -747,9 +760,18 @@ const prepareRender = async ( contextProgress: context.progress, limits: options.limits, renderer, - requestInit: (request) => ({ + requestInit: async (request) => ({ ...context, ...mounted.context, + // The render invocation is exactly what the generated Flight worker + // receives as `message.invocation`, so providers see the same shape. + providers: await mountProviders({ + explicit: context.providers, + invocation: request.invocation, + manifest: resolved.manifest, + provenance: resolved.provenance, + signal: request.signal, + }), invocation: { ...requestInvocation(request.invocation, resolved.provenance.routeId), ...context.invocation, diff --git a/packages/agent-bundle/tests/entry-shell.test.ts b/packages/agent-bundle/tests/entry-shell.test.ts index c90e2f3c4..9c23f5f05 100644 --- a/packages/agent-bundle/tests/entry-shell.test.ts +++ b/packages/agent-bundle/tests/entry-shell.test.ts @@ -17,6 +17,12 @@ import { mcpServerRuntimePath, mcpServerRuntimeSpecifier, } from '../src/build/entry-shell.ts'; +import { + executeProviders, + orderedProviders, + providerFactoryMissingMessage, + providerFailedMessage, +} from '../src/routes/provider-execution.ts'; const execFile = promisify(executeFile); @@ -617,6 +623,84 @@ it('mounts deterministic per-request providers in rendered route workers', () => expect(bridge).toContain("worker.postMessage({ id, invocation, props, request, routeId, type: 'render' })"); }); +it('keeps the generated provider loop and the in-process execution helper identical', async () => { + const providers = [ + { + id: 'provider:zeta', + name: 'zeta', + provenance: { kind: 'conventional' as const, relativePath: 'src/providers/zeta.ts' }, + source: '/project/src/providers/zeta.ts', + }, + { + id: 'provider:alpha-value', + name: 'alpha-value', + provenance: { kind: 'conventional' as const, relativePath: 'src/providers/alpha-value.ts' }, + source: '/project/src/providers/alpha-value.ts', + }, + ]; + const source = entryShellModule.generatedRenderedRouteWorkerSource({ + providers, + routes: [{ + config: {}, + id: 'cli:report', + kind: 'cli', + provenance: { kind: 'conventional', relativePath: 'src/cli/report.tsx' }, + source: '/project/src/cli/report.tsx', + }], + }); + + // Ordering: the harness manifest and the generated registry sort identically. + expect(orderedProviders(providers).map((provider) => provider.name)).toEqual(['alpha-value', 'zeta']); + expect(source.indexOf('key: "alphaValue"')).toBeLessThan(source.indexOf('key: "zeta"')); + + // Messages: the generated template literals evaluate to the helper's text. + const evaluate = (template: string, bindings: Record): string => + template.replaceAll(/\$\{([^}]+)\}/gu, (_match, expression: string) => bindings[expression] ?? `<${expression}>`); + const missing = /throw new TypeError\(`([^`]+)`\)/u.exec(source)?.[1]; + const failed = /throw new Error\(`([^`]+)`, \{ cause: error \}\)/u.exec(source)?.[1]; + expect(missing).toBeDefined(); + expect(failed).toBeDefined(); + expect(evaluate(missing!, { 'provider.key': 'alphaValue', 'provider.source': 'src/providers/alpha-value.ts' })) + .toBe(providerFactoryMissingMessage('alphaValue', 'src/providers/alpha-value.ts')); + expect(evaluate(failed!, { + 'error instanceof Error ? error.message : String(error)': 'boom', + 'provider.key': 'alphaValue', + 'provider.source': 'src/providers/alpha-value.ts', + })).toBe(providerFailedMessage('alphaValue', 'src/providers/alpha-value.ts', new Error('boom'))); + + // Behavior: processLifetime seeded first, deterministic order, fail-closed on both defects. + const lifetime = { hits: 3, instanceId: 'instance-1', pid: 42 }; + const calls: string[] = []; + const values = await executeProviders({ + invocation: { kind: 'cli', props: { args: [], command: 'report' } }, + processLifetime: lifetime, + providers: [ + { key: 'alphaValue', module: { default: (context: { invocation: unknown }) => { calls.push('alphaValue'); return context.invocation; } }, source: 'src/providers/alpha-value.ts' }, + { key: 'zeta', module: { default: async () => { calls.push('zeta'); return 'z'; } }, source: 'src/providers/zeta.ts' }, + ], + signal: new AbortController().signal, + }); + expect(Object.keys(values)).toEqual(['processLifetime', 'alphaValue', 'zeta']); + expect(values).toEqual({ + alphaValue: { kind: 'cli', props: { args: [], command: 'report' } }, + processLifetime: { hits: 3, instanceId: 'instance-1', pid: 42 }, + zeta: 'z', + }); + expect(calls).toEqual(['alphaValue', 'zeta']); + await expect(executeProviders({ + invocation: undefined, + processLifetime: lifetime, + providers: [{ key: 'zeta', module: {}, source: 'src/providers/zeta.ts' }], + signal: new AbortController().signal, + })).rejects.toThrow('Context provider "zeta" (src/providers/zeta.ts) must default-export a factory.'); + await expect(executeProviders({ + invocation: undefined, + processLifetime: lifetime, + providers: [{ key: 'zeta', module: { default: () => { throw new Error('boom'); } }, source: 'src/providers/zeta.ts' }], + signal: new AbortController().signal, + })).rejects.toThrow('Context provider "zeta" (src/providers/zeta.ts) failed: boom'); +}); + it('conditionally emits generated state mounting without leaking sqlite into volatile or stateless entries', () => { const route = { config: {}, diff --git a/packages/agent-bundle/tests/projection/cli-dispatch.test.ts b/packages/agent-bundle/tests/projection/cli-dispatch.test.ts index 2fd16d67d..d41045e26 100644 --- a/packages/agent-bundle/tests/projection/cli-dispatch.test.ts +++ b/packages/agent-bundle/tests/projection/cli-dispatch.test.ts @@ -36,10 +36,13 @@ describe('the CLI dispatch level', () => { 'harness publish-notice', 'harness strict-report', 'harness ticket', + 'harness tooling', 'harness unavailable', 'harness wait', 'inventory', 'report', + 'tooling inspect', + 'tooling report', ], proofLevel: 'cli-dispatch', }); diff --git a/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts b/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts index a3b760a85..737d1b24d 100644 --- a/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts +++ b/packages/agent-bundle/tests/projection/mcp-in-memory.test.ts @@ -31,7 +31,7 @@ describe('the in-memory MCP projection level', () => { it('registers every compiled route kind on the real generated server', async () => { const surface = await listMcpSurface(); - expect(surface.tools).toEqual(['catalog', 'context', 'echo', 'journal', 'lifecycle', 'mutation-probe', 'publish-notice', 'strict-report', 'ticket', 'unavailable', 'wait']); + expect(surface.tools).toEqual(['catalog', 'context', 'echo', 'journal', 'lifecycle', 'mutation-probe', 'publish-notice', 'strict-report', 'ticket', 'tooling', 'unavailable', 'wait']); expect(surface.prompts).toEqual(['summarize']); expect(surface.resources).toEqual(['harness://notes']); expect(surface.provenance).toMatchObject({ @@ -48,6 +48,7 @@ describe('the in-memory MCP projection level', () => { 'tool:harness/publish-notice', 'tool:harness/strict-report', 'tool:harness/ticket', + 'tool:harness/tooling', 'tool:harness/unavailable', 'tool:harness/wait', ], diff --git a/packages/agent-bundle/tests/projection/providers.test.ts b/packages/agent-bundle/tests/projection/providers.test.ts new file mode 100644 index 000000000..2a5a8a040 --- /dev/null +++ b/packages/agent-bundle/tests/projection/providers.test.ts @@ -0,0 +1,137 @@ +import { describe, expect, it } from '@rstest/core'; + +import { cliJson, invokeCli } from '../../src/test/cli.ts'; +import { AgentTestError } from '../../src/test/errors.ts'; +import { invokeMcpTool } from '../../src/test/mcp.ts'; +import { renderRoute } from '../../src/test/render.ts'; +import { testManifest } from '../../src/test/registry.ts'; + +/** + * Conventional request context providers reach every harness request scope + * the way they reach every generated request scope (#313, #366): discovered + * from the compiled manifest, executed once per request in the generated + * order, and mounted at `providers.` beside the framework-owned + * `processLifetime`. A test that passes `context.providers` opts out and the + * explicit map is used verbatim. + */ +describe('conventional providers through the harness', () => { + it('names the compiled providers in the manifest in the generated execution order', () => { + const manifest = testManifest(); + + expect(manifest.providers).toEqual([{ + id: 'provider:library-tooling', + key: 'libraryTooling', + name: 'library-tooling', + relativePath: 'src/providers/library-tooling.ts', + source: expect.stringMatching(/route-harness[\\/]src[\\/]providers[\\/]library-tooling\.ts$/u), + }]); + }); + + it('mounts providers for a plain routed CLI command with the cli invocation', async () => { + const run = await invokeCli(['tooling', 'inspect']); + + expect(run.exitCode).toBe(0); + expect(run.stderr).toBe(''); + expect(cliJson(run)).toEqual({ + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: { kind: 'cli', surface: 'tooling inspect', tool: 'ffprobe 6.1' }, + processLifetime: { hits: expect.any(Number), instanceId: expect.any(String), pid: process.pid }, + }); + }); + + it('mounts providers for a rendered routed CLI command with the cli invocation', async () => { + const run = await invokeCli(['tooling', 'report', '--json']); + + expect(run.exitCode).toBe(0); + expect(run.stderr).toBe(''); + expect(cliJson(run)).toEqual({ + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: { kind: 'cli', surface: 'tooling report', tool: 'ffprobe 6.1' }, + }); + }); + + it('mounts providers for a projected MCP command with the tool invocation', async () => { + const run = await invokeCli(['harness', 'tooling', '--json']); + + expect(run.exitCode).toBe(0); + expect(cliJson(run)).toEqual({ + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: { kind: 'tool', surface: 'tool:harness/tooling', tool: 'ffprobe 6.1' }, + }); + }); + + it('mounts providers for an MCP route through the real in-memory server', async () => { + const call = await invokeMcpTool('tooling'); + + expect(call.isError).toBe(false); + expect(call.structuredContent).toEqual({ + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: { kind: 'tool', surface: 'tool:harness/tooling', tool: 'ffprobe 6.1' }, + }); + }); + + it('mounts providers for an MCP route at the route-unit level', async () => { + const rendered = await renderRoute('tool:harness/tooling'); + + expect(rendered.result).toEqual({ + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: { kind: 'tool', surface: 'tool:harness/tooling', tool: 'ffprobe 6.1' }, + }); + }); + + it('mounts providers for a rendered script with the script invocation', async () => { + const rendered = await renderRoute('script:tooling-summary', { args: ['--fast', 'a.mp4'] }); + + expect(rendered.result).toEqual({ + arguments: 2, + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: { kind: 'script', surface: 'script:tooling-summary', tool: 'ffprobe 6.1' }, + }); + }); + + it('counts every harness request in one process identity', async () => { + const first = cliJson(await invokeCli(['tooling', 'inspect'])) as { processLifetime: { hits: number; instanceId: string } }; + await renderRoute('tool:harness/tooling'); + const second = cliJson(await invokeCli(['tooling', 'inspect'])) as { processLifetime: { hits: number; instanceId: string } }; + + expect(second.processLifetime.instanceId).toBe(first.processLifetime.instanceId); + expect(second.processLifetime.hits).toBeGreaterThanOrEqual(first.processLifetime.hits + 2); + }); + + it('uses an explicit context.providers map verbatim instead of discovering providers', async () => { + const [plain, rendered, tool] = await Promise.all([ + invokeCli(['tooling', 'inspect'], { + context: { providers: { libraryTooling: 'stubbed', processLifetime: { hits: 1, instanceId: 'test', pid: 1 } } }, + }), + renderRoute('script:tooling-summary', { context: { providers: { other: true } } }), + invokeMcpTool('tooling', { context: { providers: {} } }), + ]); + + expect(cliJson(plain)).toEqual({ + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: 'stubbed', + processLifetime: { hits: 1, instanceId: 'test', pid: 1 }, + }); + expect(rendered.result).toEqual({ arguments: 0, keys: ['other'] }); + expect(tool.structuredContent).toEqual({ keys: [] }); + }); + + it('fails a request closed when a provider factory throws, naming the provider like the generated scope', async () => { + const message = 'Context provider "libraryTooling" (src/providers/library-tooling.ts) failed: ffprobe is not installed'; + + const run = await invokeCli(['harness', 'tooling', '--input', '{"failProvider":true}']); + expect(run.exitCode).toBe(1); + expect(run.stdout).toBe(''); + expect(run.stderr).toContain(message); + + let error: unknown; + try { + await renderRoute('tool:harness/tooling', { input: { failProvider: true } }); + } catch (caught) { + error = caught; + } + expect(error).toBeInstanceOf(AgentTestError); + expect((error as AgentTestError).code).toBe('render-failed'); + expect((error as AgentTestError).message).toContain(message); + }); +}); diff --git a/packages/agent-bundle/tests/support/contract-matrix-fixtures.ts b/packages/agent-bundle/tests/support/contract-matrix-fixtures.ts index 34a456dc0..0cd1bb063 100644 --- a/packages/agent-bundle/tests/support/contract-matrix-fixtures.ts +++ b/packages/agent-bundle/tests/support/contract-matrix-fixtures.ts @@ -101,6 +101,7 @@ export const routeHarnessContractFixtures = (): Record { 'cli:db/migrate', 'cli:inventory', 'cli:report', + 'cli:tooling/inspect', + 'cli:tooling/report', 'event:tool/after', 'prompt:harness/summarize', 'resource:harness/notes', + 'script:tooling-summary', 'tool:harness/catalog', 'tool:harness/context', 'tool:harness/echo', @@ -79,10 +82,18 @@ describe('the compiled test manifest', () => { 'tool:harness/publish-notice', 'tool:harness/strict-report', 'tool:harness/ticket', + 'tool:harness/tooling', 'tool:harness/unavailable', 'tool:harness/wait', ]); expect(manifest.diagnostics).toEqual([]); + expect(manifest.providers).toEqual([{ + id: 'provider:library-tooling', + key: 'libraryTooling', + name: 'library-tooling', + relativePath: 'src/providers/library-tooling.ts', + source: resolve(fixtureRoot, 'src/providers/library-tooling.ts'), + }]); expect(manifest.routes['tool:harness/echo']).toEqual({ config: { annotations: { readOnlyHint: true }, @@ -157,6 +168,24 @@ describe('the compiled test manifest', () => { rendered: true, routeId: 'cli:report', }, + { + aliases: [], + description: 'Reports the request providers a plain command observes.', + exitCode: 'zero', + options: [], + path: ['tooling', 'inspect'], + rendered: false, + routeId: 'cli:tooling/inspect', + }, + { + aliases: [], + description: 'Renders the request providers a rendered command observes.', + exitCode: 'zero', + options: [], + path: ['tooling', 'report'], + rendered: true, + routeId: 'cli:tooling/report', + }, ]); const inputOption = { description: 'Tool input as one JSON object.', @@ -198,6 +227,7 @@ describe('the compiled test manifest', () => { projected('publish-notice', 'Publishes a durable notice for a later session event.', true), projected('strict-report', 'Returns a closed-object report that rejects unknown serialized keys.', true), projected('ticket', 'Returns a cargo-conductor-shaped ticket status with optional diagnostics fields.', true), + projected('tooling', 'Reports the request providers an MCP tool observes.', false), projected('unavailable', 'Returns a typed unavailable result for projection checks.', true), projected('wait', 'Waits until aborted or holdMs elapses, for cancellation contract proof.', true), ]); @@ -299,6 +329,15 @@ describe('the generated route registry', () => { expect(source).toContain('app:harness/panel'); }); + it('registers a loader for every conventional provider so the harness mounts them like the entry shell', () => { + const providerLoaders = /providerLoaders: \{\n(?[\s\S]*?)\n {2}\},/u.exec(source)?.groups?.body ?? ''; + + expect(providerLoaders).toContain('"provider:library-tooling": () => import('); + expect(providerLoaders).toContain('/src/providers/library-tooling.ts'); + // A project without providers emits no loader table at all. + expect(routeTestSetupSource({ ...manifest, providers: undefined })).not.toContain('providerLoaders'); + }); + it('carries the manifest and the registry version the helpers require', () => { expect(source).toContain(`version: ${String(AGENT_TEST_REGISTRY_VERSION)}`); expect(source).toContain('globalThis[Symbol.for("agent-bundle/test-route-registry")]'); From 459c3e5b1d673423a70115076851ccac0c5ad90b Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 06:02:20 +0000 Subject: [PATCH 02/13] test(workbench): wait on the watcher rebuild instead of retrying examples-real edits Each source edit paired a file write with an immediate manual rebuild, so the watcher's own rebuild of the same write raced it for a second epoch whose timing depended on load; { retry: 2 } absorbed the fallout. Edits now go through replaceWatchedSourceAndAwaitRebuild: one atomic replacement, then a wait on the coordinator's published build attempt, so one edit is exactly one build and the retries are gone. Refs #122, #200, #329. --- docs/local-ci.md | 12 +++ .../tests/support/watched-files.ts | 63 +++++++++++ .../tests/watched-files-support.test.ts | 100 ++++++++++++++++++ .../workbench/tests/examples-real.e2e.test.ts | 89 +++++++--------- 4 files changed, 216 insertions(+), 48 deletions(-) create mode 100644 packages/agent-bundle/tests/watched-files-support.test.ts diff --git a/docs/local-ci.md b/docs/local-ci.md index 26246af4f..dd73a4cbe 100644 --- a/docs/local-ci.md +++ b/docs/local-ci.md @@ -175,6 +175,18 @@ machine is exactly the contention that scale exists for. Exporting running other heavy work) overrides the default; the integration config never lets it drop below what its own pool shape requires. +Load-sensitive failures are fixed at their cause, never absorbed with a +per-test `retry`. The recurring shape is a test that acts before the product +has published the state it is about to assert on; the fix is to wait on the +product's own readiness signal. Precedents: the dev watcher's stat-signature +dedupe (#122/#329), content-identity reload announcements (#200/#332), and +the `examples-real.e2e` source edits, which used to pair a file write with an +immediate manual rebuild and so raced the watcher's own rebuild of the same +write for a second epoch. Those edits now go through +`replaceWatchedSourceAndAwaitRebuild` (`packages/agent-bundle/tests/support/watched-files.ts`): +one atomic replacement, then a wait on the coordinator's published build +attempt, so one edit is exactly one build. + ## What is deliberately not covered - **dependency-review** runs as a GitHub-side action against the GitHub diff --git a/packages/agent-bundle/tests/support/watched-files.ts b/packages/agent-bundle/tests/support/watched-files.ts index 35fe2a1fc..04b50c0b3 100644 --- a/packages/agent-bundle/tests/support/watched-files.ts +++ b/packages/agent-bundle/tests/support/watched-files.ts @@ -1,5 +1,8 @@ import { rename, writeFile } from 'node:fs/promises'; import { basename, join } from 'node:path'; +import { setTimeout as sleep } from 'node:timers/promises'; + +import type { CompletedBuildAttempt, ProjectStatus } from '../../src/dev/types.ts'; /** * Replaces a file the dev server may read concurrently (watcher events or an @@ -15,3 +18,63 @@ export const replaceWatchedSource = async (projectRoot: string, path: string, co await writeFile(temporary, content); await rename(temporary, path); }; + +/** The dev-server session surface the watcher-rebuild wait reads; `DevServerSession` satisfies it. */ +export interface WatchedBuildSession { + status(): ProjectStatus; +} + +export interface AwaitWatcherRebuildOptions { + /** Upper bound for the watcher's debounce plus one full development rebuild. */ + readonly timeoutMs: number; +} + +const attemptIds = (status: ProjectStatus): ReadonlySet => { + const ids = new Set(); + if (status.build.state === 'building') ids.add(status.build.activeAttempt.id); + if ('lastAttempt' in status.build && status.build.lastAttempt !== undefined) ids.add(status.build.lastAttempt.id); + return ids; +}; + +const pollIntervalMs = 25; + +/** + * Replaces one watched source and waits for the dev server's own + * watcher-driven rebuild of that write to finish, returning the completed + * attempt. This is the readiness signal a source edit needs: the coordinator + * publishes every attempt through `status()`, and the watcher mints exactly + * one invalidation per write (path-signature dedupe, #329), so the first + * completed attempt the session did not know before the write is the + * write's build. Issuing a manual rebuild in the same window instead races + * the watcher for a second, redundant epoch whose arrival time depends on + * load — the race behind the retired `{ retry: 2 }` guards in + * `examples-real.e2e.test.ts`. + */ +export const replaceWatchedSourceAndAwaitRebuild = async ( + session: WatchedBuildSession, + projectRoot: string, + path: string, + content: string, + options: AwaitWatcherRebuildOptions, +): Promise => { + const known = attemptIds(session.status()); + await replaceWatchedSource(projectRoot, path, content); + const deadline = Date.now() + options.timeoutMs; + for (;;) { + const status = session.status(); + if ( + status.build.state !== 'building' + && status.build.lastAttempt !== undefined + && !known.has(status.build.lastAttempt.id) + ) { + return status.build.lastAttempt; + } + if (Date.now() >= deadline) { + throw new Error( + `Timed out after ${String(options.timeoutMs)}ms waiting for the watcher rebuild of ${path}; ` + + `known attempts ${JSON.stringify([...known])}; last status ${JSON.stringify(status.build)}.`, + ); + } + await sleep(pollIntervalMs); + } +}; diff --git a/packages/agent-bundle/tests/watched-files-support.test.ts b/packages/agent-bundle/tests/watched-files-support.test.ts new file mode 100644 index 000000000..42d2ee38c --- /dev/null +++ b/packages/agent-bundle/tests/watched-files-support.test.ts @@ -0,0 +1,100 @@ +import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; + +import { afterEach, beforeEach, describe, expect, it } from '@rstest/core'; + +import type { CompletedBuildAttempt, ProjectStatus, RunningBuildAttempt } from '../src/dev/types.ts'; +import { replaceWatchedSourceAndAwaitRebuild } from './support/watched-files.ts'; + +const running = (id: string): RunningBuildAttempt => Object.freeze({ + diagnostics: Object.freeze([]), + id, + outcome: 'running', + sourceRevision: 'rev', + startedAt: '2026-09-02T00:00:00.000Z', +}); + +/** A completed attempt; failed so the fake needs no artifact epoch. The wait is outcome-agnostic. */ +const completed = (id: string): CompletedBuildAttempt => Object.freeze({ + completedAt: '2026-09-02T00:00:01.000Z', + diagnostics: Object.freeze([ + Object.freeze({ code: 'AB7201', message: `attempt ${id} failed`, severity: 'error' as const }), + ] as const), + id, + outcome: 'failed', + sourceRevision: 'rev', + startedAt: '2026-09-02T00:00:00.000Z', +}); + +const idle = (lastAttempt?: CompletedBuildAttempt): ProjectStatus => Object.freeze({ + artifact: Object.freeze({ state: 'missing' }), + build: Object.freeze(lastAttempt === undefined ? { state: 'idle' } : { lastAttempt, state: 'idle' }), + source: Object.freeze({ diagnostics: Object.freeze([]), state: 'ready' }), +}); + +const building = (active: RunningBuildAttempt, lastAttempt?: CompletedBuildAttempt): ProjectStatus => Object.freeze({ + artifact: Object.freeze({ state: 'missing' }), + build: Object.freeze({ activeAttempt: active, ...(lastAttempt === undefined ? {} : { lastAttempt }), state: 'building' }), + source: Object.freeze({ diagnostics: Object.freeze([]), state: 'ready' }), +}); + +/** + * The readiness wait behind the `examples-real.e2e` source edits: the first + * completed attempt the session did not already know is the write's build. + * A session that reports the pre-write attempt, or a still-running one, is + * not ready yet. + */ +describe('replaceWatchedSourceAndAwaitRebuild', () => { + let root: string; + let project: string; + + beforeEach(async () => { + root = await mkdtemp(join(tmpdir(), 'agent-bundle-watched-files-')); + project = join(root, 'project'); + await mkdir(project); + }); + + afterEach(async () => { + await rm(root, { force: true, recursive: true }); + }); + + it('returns the first completed attempt that was unknown before the write, after the write landed', async () => { + const before = completed('attempt-0'); + const sequence: ProjectStatus[] = [ + idle(before), + idle(before), + building(running('attempt-1'), before), + idle(completed('attempt-1')), + ]; + let reads = 0; + const session = { status: () => sequence[Math.min(reads++, sequence.length - 1)]! }; + const path = join(project, 'source.ts'); + + const attempt = await replaceWatchedSourceAndAwaitRebuild(session, project, path, 'export const value = 2;\n', { timeoutMs: 5_000 }); + + expect(attempt.id).toBe('attempt-1'); + expect(attempt.outcome).toBe('failed'); + expect(await readFile(path, 'utf8')).toBe('export const value = 2;\n'); + // The pre-write status read seeds the known set; the wait began only after the write. + expect(reads).toBeGreaterThanOrEqual(4); + }); + + it('does not accept the pre-write attempt as the write\'s build', async () => { + const before = completed('attempt-0'); + const session = { status: () => idle(before) }; + + await expect(replaceWatchedSourceAndAwaitRebuild(session, project, join(project, 'source.ts'), 'x', { timeoutMs: 120 })) + .rejects.toThrow(/Timed out after 120ms waiting for the watcher rebuild .*known attempts \["attempt-0"\]/u); + }); + + it('treats an attempt that was already running before the write as known', async () => { + const active = running('attempt-1'); + const sequence: ProjectStatus[] = [building(active), idle(completed('attempt-1'))]; + let reads = 0; + const session = { status: () => sequence[Math.min(reads++, sequence.length - 1)]! }; + + await expect(replaceWatchedSourceAndAwaitRebuild(session, project, join(project, 'source.ts'), 'x', { timeoutMs: 120 })) + .rejects.toThrow(/known attempts \["attempt-1"\]/u); + }); +}); diff --git a/packages/workbench/tests/examples-real.e2e.test.ts b/packages/workbench/tests/examples-real.e2e.test.ts index 4a9d87273..ce122f0b9 100644 --- a/packages/workbench/tests/examples-real.e2e.test.ts +++ b/packages/workbench/tests/examples-real.e2e.test.ts @@ -15,10 +15,36 @@ import { writeExampleReport, } from './support/example-acceptance.ts'; import { timeScale } from '../../agent-bundle/tests/support/time-scale.ts'; -import { replaceWatchedSource } from '../../agent-bundle/tests/support/watched-files.ts'; +import { + replaceWatchedSourceAndAwaitRebuild, + type WatchedBuildSession, +} from '../../agent-bundle/tests/support/watched-files.ts'; import { buildWorkbench, e2e, workbenchAssets, workbenchUrl } from './support/workbench-e2e.ts'; const browserTimeout = 15_000 * timeScale; +/** One watcher debounce plus a full development rebuild of an example under gate load. */ +const rebuildTimeout = 60_000 * timeScale; + +/** + * Edits one watched source and waits for the dev server's own rebuild of that + * edit to complete before the browser is asked about it. A source write must + * not be paired with an immediate manual rebuild: the watcher rebuilds the + * same write on its own, and two builds per edit mint two epochs whose + * relative timing depends on load — the second one flips the Workbench's + * build identity while it may still be loading capabilities for the first. + * Waiting on the coordinator's published attempt makes one edit exactly one + * build, so no retry is needed to absorb that race. + */ +const editWatchedSource = async ( + server: WatchedBuildSession, + projectRoot: string, + path: string, + content: string, + expectedOutcome: 'failed' | 'succeeded', +): Promise => { + const attempt = await replaceWatchedSourceAndAwaitRebuild(server, projectRoot, path, content, { timeoutMs: rebuildTimeout }); + expect(attempt.outcome).toBe(expectedOutcome); +}; const waitForExampleValue = async ( page: Parameters[0], @@ -40,20 +66,6 @@ const waitForExampleValue = async ( return value; }; -const rebuildFromCurrentPage = async (page: Parameters[0]): Promise => { - const status = await page.evaluate(async () => { - const sessionResponse = await fetch('/api/project/session'); - const session = await sessionResponse.json() as { readonly token: string }; - const response = await fetch('/api/project/rebuild', { - body: JSON.stringify({ paths: [] }), - headers: { 'content-type': 'application/json', 'x-agent-bundle-session': session.token }, - method: 'POST', - }); - return response.status; - }); - expect(status).toBe(200); -}; - e2e('drives the populated Skills Starter in real Chrome', { timeout: 90_000 }, async ({ page }) => { await buildWorkbench(); const server = await startDevServer({ @@ -108,9 +120,7 @@ e2e('drives the populated Skills Starter in real Chrome', { timeout: 90_000 }, a } }); -// #122's delayed duplicate event is signature-gated; this retry still covers the first -// Chokidar event racing the immediate manual rebuild after each source write. -e2e('reveals, retains, repairs, and removes capabilities without reloading Chrome', { retry: 2, timeout: 120_000 }, async ({ page }) => { +e2e('reveals, retains, repairs, and removes capabilities without reloading Chrome', { timeout: 120_000 }, async ({ page }) => { await buildWorkbench(); const project = await copyExample('skills-starter'); const configPath = join(project.root, 'agent-bundle.config.ts'); @@ -137,8 +147,7 @@ e2e('reveals, retains, repairs, and removes capabilities without reloading Chrom await expect(page.getByRole('link', { name: 'Hooks', exact: true })).toHaveCount(0, { timeout: browserTimeout }); await expect(page.getByRole('link', { name: 'Playground', exact: true })).toHaveCount(0, { timeout: browserTimeout }); - await writeFile(configPath, hookConfig); - await rebuildFromCurrentPage(page); + await editWatchedSource(server, project.root, configPath, hookConfig, 'succeeded'); await expect(page.getByRole('link', { name: 'Hooks', exact: true })).toBeVisible({ timeout: browserTimeout }); await expect(page.getByRole('link', { name: 'Playground', exact: true })).toBeVisible({ timeout: browserTimeout }); await page.getByRole('link', { name: 'Hooks', exact: true }).click(); @@ -146,8 +155,7 @@ e2e('reveals, retains, repairs, and removes capabilities without reloading Chrom await expect(page.locator('#hook-binding option')).not.toHaveCount(0, { timeout: browserTimeout }); await captureExampleState(page, 'skills-starter', 'capability-revealed'); - await writeFile(hookSource, 'export default () => ({\n'); - await rebuildFromCurrentPage(page); + await editWatchedSource(server, project.root, hookSource, 'export default () => ({\n', 'failed'); await page.getByRole('link', { name: 'Overview', exact: true }).click(); await waitForSettledWorkbench(page); await expect(page.getByRole('heading', { name: /Diagnostics \([1-9]/u })).toBeVisible({ timeout: browserTimeout }); @@ -156,8 +164,7 @@ e2e('reveals, retains, repairs, and removes capabilities without reloading Chrom await expect(page.getByRole('link', { name: 'Playground', exact: true })).toBeVisible({ timeout: browserTimeout }); await captureExampleState(page, 'skills-starter', 'capability-stale'); - await writeFile(hookSource, healthyHook); - await rebuildFromCurrentPage(page); + await editWatchedSource(server, project.root, hookSource, healthyHook, 'succeeded'); await expect(page.getByRole('heading', { name: 'Diagnostics (0)' })).toBeVisible({ timeout: browserTimeout }); await expect(page.locator('.build-health')).toContainText('Current build', { timeout: browserTimeout }); await captureExampleState(page, 'skills-starter', 'capability-repaired'); @@ -165,8 +172,7 @@ e2e('reveals, retains, repairs, and removes capabilities without reloading Chrom await page.getByRole('link', { name: 'Hooks', exact: true }).click(); await waitForSettledWorkbench(page); await expect(page.locator('#hook-binding option')).not.toHaveCount(0, { timeout: browserTimeout }); - await writeFile(configPath, originalConfig); - await rebuildFromCurrentPage(page); + await editWatchedSource(server, project.root, configPath, originalConfig, 'succeeded'); await expect(page).toHaveURL(new URL('#overview', server.url).href, { timeout: browserTimeout }); await expect(page.getByRole('link', { name: 'Hooks', exact: true })).toHaveCount(0, { timeout: browserTimeout }); await expect(page.getByRole('link', { name: 'Playground', exact: true })).toHaveCount(0, { timeout: browserTimeout }); @@ -179,9 +185,7 @@ e2e('reveals, retains, repairs, and removes capabilities without reloading Chrom } }); -// #122's delayed duplicate event is signature-gated; this retry still covers the first -// Chokidar event racing the immediate manual rebuild after each source write. -e2e('drives Hooks, scripts, logs, diagnostics, and repair in real Chrome', { retry: 2, timeout: 150_000 }, async ({ page }) => { +e2e('drives Hooks, scripts, logs, diagnostics, and repair in real Chrome', { timeout: 150_000 }, async ({ page }) => { await buildWorkbench(); const project = await copyExample('hooks-and-scripts'); const hookSource = join(project.root, 'src', 'hooks', 'session-start.ts'); @@ -270,25 +274,18 @@ e2e('drives Hooks, scripts, logs, diagnostics, and repair in real Chrome', { ret await expect(page.locator('.logs-details').first()).toHaveAttribute('open', ''); await captureExampleState(page, 'hooks-and-scripts', 'logs-populated'); - await writeFile(hookSource, 'export default () => ({\n'); + // The stale-diagnostic and repair journey rides the watcher's own rebuild + // of each edit; the Rebuild button's manual path is overview.e2e's claim. await page.getByRole('link', { name: 'Overview' }).click(); - const failedRebuild = page.waitForResponse((response) => response.url() === `${server.url}/api/project/rebuild` && response.request().method() === 'POST'); - await page.getByRole('button', { name: 'Rebuild' }).click(); - await failedRebuild; + await waitForSettledWorkbench(page); + await editWatchedSource(server, project.root, hookSource, 'export default () => ({\n', 'failed'); await expect(page.getByRole('heading', { name: /Diagnostics \([1-9]/u })).toBeVisible({ timeout: browserTimeout }); await expect(page.locator('.build-health')).toContainText('Last good build', { timeout: browserTimeout }); - await page.waitForTimeout(500); - await expect(page.locator('.build-health')).toContainText('Last good build', { timeout: browserTimeout }); await captureExampleState(page, 'hooks-and-scripts', 'diagnostic-stale'); - await writeFile(hookSource, healthyHook); - const repaired = page.waitForResponse((response) => response.url() === `${server.url}/api/project/rebuild` && response.request().method() === 'POST' && response.ok()); - await page.getByRole('button', { name: 'Rebuild' }).click(); - await repaired; + await editWatchedSource(server, project.root, hookSource, healthyHook, 'succeeded'); await expect(page.getByRole('heading', { name: 'Diagnostics (0)' })).toBeVisible({ timeout: browserTimeout }); await expect(page.locator('.build-health')).toContainText('Current build', { timeout: browserTimeout }); - await page.waitForTimeout(500); - await expect(page.locator('.build-health')).toContainText('Current build', { timeout: browserTimeout }); await captureExampleState(page, 'hooks-and-scripts', 'diagnostic-repaired'); await expectHealthyExamplePage(ledger); await writeExampleReport(); @@ -575,9 +572,7 @@ e2e('drives every populated MCP App workflow surface in real Chrome', { timeout: } }); -// #122's delayed duplicate event is signature-gated; this retry still covers the first -// Chokidar event racing the immediate manual rebuild after each staged source replacement. -e2e('renders the flagship compiled route catalog by server and kind in real Chrome', { retry: 2, timeout: 150_000 }, async ({ page }) => { +e2e('renders the flagship compiled route catalog by server and kind in real Chrome', { timeout: 150_000 }, async ({ page }) => { await buildWorkbench(); const project = await copyExample('audiobook-curator'); const conversionSource = join(project.root, 'src', 'conversion.ts'); @@ -707,8 +702,7 @@ e2e('renders the flagship compiled route catalog by server and kind in real Chro // A prepared source revision can move ahead while a failed rebuild keeps // the published epoch intact. Reloading the same browser page re-reads that // prepared manifest and must identify it as stale until a repair publishes. - await replaceWatchedSource(project.root, conversionSource, `${healthyConversion}\nconst = ;\n`); - await rebuildFromCurrentPage(page); + await editWatchedSource(server, project.root, conversionSource, `${healthyConversion}\nconst = ;\n`, 'failed'); await page.reload(); await waitForSettledWorkbench(page); await expect(page.locator('.route-state')).toHaveText('stale', { timeout: browserTimeout }); @@ -718,8 +712,7 @@ e2e('renders the flagship compiled route catalog by server and kind in real Chro ); await captureExampleState(page, 'audiobook-curator', 'routes-catalog-stale'); - await replaceWatchedSource(project.root, conversionSource, healthyConversion); - await rebuildFromCurrentPage(page); + await editWatchedSource(server, project.root, conversionSource, healthyConversion, 'succeeded'); await waitForSettledWorkbench(page); await expect(page.locator('.route-state')).toHaveText('current', { timeout: browserTimeout }); await expect(page.locator('.routes-page-heading')).toContainText( From b0255d89d793d98f573d9cc1f3152f81be12ef77 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 06:18:42 +0000 Subject: [PATCH 03/13] test(route-unit): reconcile the #371 provider seam pin with harness auto-mounting Explicit context.providers still mounts verbatim; a module rendered directly now observes the framework-owned processLifetime like a generated scope without providers, and manifest routes execute conventional providers. --- docs/entry-conventions.md | 28 ++++++++++--------- .../tests/route-unit/render-route.test.ts | 10 ++++--- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/docs/entry-conventions.md b/docs/entry-conventions.md index d3a5b2d5e..9c5b352b0 100644 --- a/docs/entry-conventions.md +++ b/docs/entry-conventions.md @@ -172,19 +172,21 @@ expected degradation should return an honest unavailable-shaped value instead of throwing. `invocation.kind` stays surface-specific (`tool`, `event`, `cli`, `script`), so a provider can branch on the entry surface deliberately. `processLifetime` is reserved for the framework-owned process identity and hit -counter, so provider filenames must not derive that key. The `agent-bundle/test` -harness mounts the same providers, in the same order and with the same -fail-closed semantics, for every manifest-backed helper; a test passes -`context.providers` to substitute an explicit map instead. - -Route-unit and CLI-dispatch tests inject provider values through the same -`context` seam as identity axes (`renderRoute(id, { context: { providers: -{ library: fixture } } })`); the harness never executes conventional provider -modules, so a test chooses exactly the values a component observes. Once the -generated `.agent-bundle/routes.d.ts` augmentation declares provider keys, the -harness `options` and its `context.providers` become required (as does -`providers` on a direct `runAgentRequest`), so omitting a fixture the route's -types promise is a compile error rather than a runtime `undefined`. +counter, so provider filenames must not derive that key. + +The `agent-bundle/test` harness mounts the same providers, in the same order +and with the same fail-closed semantics, for every manifest-backed helper +(`renderRoute`, `renderRouteEvents`, `invokeCli`, and the in-memory MCP +helpers), so a route test observes what the artifact would mount. A test that +wants to choose the values instead injects them through the same `context` +seam as identity axes (`renderRoute(id, { context: { providers: { library: +fixture } } })`): an explicit map is mounted verbatim and no conventional +provider module executes. A module rendered directly (no compiled manifest) +has no project to discover, so it observes only `processLifetime`. Once the +generated `.agent-bundle/routes.d.ts` augmentation declares provider keys, an +explicit `context.providers` map must carry every declared key (as must +`providers` on a direct `runAgentRequest`), so a fixture that omits a value the +route's types promise is a compile error rather than a runtime `undefined`. ### Handler request context diff --git a/packages/agent-bundle/tests/route-unit/render-route.test.ts b/packages/agent-bundle/tests/route-unit/render-route.test.ts index ca1ed8511..9343d3a04 100644 --- a/packages/agent-bundle/tests/route-unit/render-route.test.ts +++ b/packages/agent-bundle/tests/route-unit/render-route.test.ts @@ -263,7 +263,7 @@ describe('renderRoute through the real renderer', () => { .toHaveValue(undefined); }); - it('mounts provider fixture values through the context seam instead of executing provider modules', async () => { + it('mounts explicit provider fixture values through the context seam instead of discovering providers', async () => { const library = { stages: ['discover', 'curate'], tooling: { ffmpeg: { available: false } } }; const Providers = async (): Promise => { const { providers } = await agent(); @@ -287,12 +287,14 @@ describe('renderRoute through the real renderer', () => { library, }); - // A render without fixtures observes an empty, frozen provider map — the - // harness never runs conventional src/providers modules on the test's behalf. + // A module rendered directly has no compiled manifest, so there is nothing + // to discover: it observes only the framework-owned process identity, the + // same map a generated scope without providers mounts. Manifest routes + // execute the project's conventional providers (projection/providers.test.ts). const unfixtured = await renderRoute({ default: Providers as never }, { routeId: 'tool:harness/providers (module)', }); - expectDocument(unfixtured).toHaveValue({ frozen: true, keys: [], library: undefined }); + expectDocument(unfixtured).toHaveValue({ frozen: true, keys: ['processLifetime'], library: undefined }); }); it('serves useAgent() synchronously inside a rendered Server Component', async () => { From b86acd9add0e64949a662d0e5e557f0d3972030d Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 06:29:15 +0000 Subject: [PATCH 04/13] test(workbench): replace the logs-real source edit atomically A truncating writeFile can split into two watcher invalidations under load, logging "Project source changed." twice and tripping the strict locator; the shared atomic replacement makes one edit one invalidation. --- packages/workbench/tests/logs-real.e2e.test.ts | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/workbench/tests/logs-real.e2e.test.ts b/packages/workbench/tests/logs-real.e2e.test.ts index 8ad816c69..9628f163c 100644 --- a/packages/workbench/tests/logs-real.e2e.test.ts +++ b/packages/workbench/tests/logs-real.e2e.test.ts @@ -1,11 +1,10 @@ -import { writeFile } from 'node:fs/promises'; - import { expect } from '@rstest/playwright'; import { createWorkbenchAssetSource } from '../../agent-bundle/src/dev/workbench-assets.ts'; import { startDevServer } from '../../agent-bundle/src/dev/workbench-server.ts'; import { createProjectFixture, removeProjectFixture } from '../../agent-bundle/tests/helpers/project-fixture.ts'; import { timeScale } from '../../agent-bundle/tests/support/time-scale.ts'; +import { replaceWatchedSource } from '../../agent-bundle/tests/support/watched-files.ts'; import { buildWorkbench, e2e, workbenchAssets, workbenchUrl } from './support/workbench-e2e.ts'; const browserTimeout = 12_000 * timeScale; @@ -31,7 +30,9 @@ e2e('shows real producer logs with replay, filters, redaction, responsive layout const replay = await (await replayed).json() as { readonly replay: Readonly<{ readonly records: readonly unknown[] }> }; expect(replay.replay.records.length).toBeGreaterThan(0); - await writeFile(project.skillSource, `${project.skillMarkdown}\nSource change for Logs E2E.\n`); + // One atomic replacement is one watcher invalidation; a truncating write + // can split into two under load and log "Project source changed." twice. + await replaceWatchedSource(project.root, project.skillSource, `${project.skillMarkdown}\nSource change for Logs E2E.\n`); await expect(page.getByText('Project source changed.')).toBeVisible({ timeout: browserTimeout }); await expect(page.locator('.logs-entries > li').first()).toBeVisible({ timeout: browserTimeout }); await expect(page.locator('.logs-entry-level').first()).toBeVisible(); From a60c2982164a1c9c6b99fddea9fe6813e39bf7f1 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 07:00:00 +0000 Subject: [PATCH 05/13] fix(test): derive executable surface for harness invocations and bump registry version MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit renderRoute now hands providers and the request scope the surface the generated entries record — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id, so providers that branch on `command`/`name` behave identically in the harness and the artifact. The test registry version moves to 4 because the layout gained `providerLoaders`. The audiobook-curator degraded-catalog test opts out of the auto-mounted library provider explicitly. --- .../test-harness-conventional-providers.md | 2 +- .../tests/route-unit/context.test.ts | 3 + .../artifact/agent-bundle.hooks.json | 1 + .../artifact/agent-bundle.manifest.json | 1 + .../claude/.claude-plugin/marketplace.json | 1 + .../claude/.claude-plugin/plugin.json | 1 + .../artifact/claude/INSTALL.md | 18 + .../assets/release/release-manifest.json | 21 + .../claude/assets/release/risk-register.json | 16 + .../artifact/claude/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 251 + .../claude/scripts/verify-release.mjs | 54 + .../codex/.agents/plugins/marketplace.json | 1 + .../artifact/codex/.codex-plugin/plugin.json | 1 + .../artifact/codex/INSTALL.md | 16 + .../assets/release/release-manifest.json | 21 + .../codex/assets/release/risk-register.json | 16 + .../artifact/codex/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 254 + .../artifact/codex/scripts/verify-release.mjs | 54 + .../artifact/portable/INSTALL.md | 19 + .../assets/release/release-manifest.json | 21 + .../assets/release/risk-register.json | 16 + .../artifact/portable/install.mjs | 80 + .../artifact/portable/plugin.json | 1 + .../artifact/portable/scripts/detect-risk.mjs | 35 + .../portable/scripts/verify-release.mjs | 54 + .../mcp-app/artifact/agent-bundle.hooks.json | 1 + .../artifact/agent-bundle.manifest.json | 1 + .../claude/.claude-plugin/marketplace.json | 1 + .../claude/.claude-plugin/plugin.json | 1 + examples/mcp-app/artifact/claude/.mcp.json | 1 + examples/mcp-app/artifact/claude/INSTALL.md | 18 + .../assets/evals/fixtures/status/result.json | 9 + .../mcp-app/artifact/claude/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 251 + .../claude/mcp/mcp-status-073c1634.mjs | 30761 +++++++++++++++ .../claude/scripts/check-service-fixture.mjs | 60 + .../claude/skills/service-readiness/SKILL.md | 33 + .../assets/readiness-report.md | 22 + .../references/status-policy.md | 22 + .../codex/.agents/plugins/marketplace.json | 1 + .../artifact/codex/.codex-plugin/plugin.json | 1 + examples/mcp-app/artifact/codex/.mcp.json | 1 + examples/mcp-app/artifact/codex/INSTALL.md | 16 + .../assets/evals/fixtures/status/result.json | 9 + .../mcp-app/artifact/codex/hooks/hooks.json | 1 + .../session-start-session-start-7ab7e8a5.mjs | 254 + .../codex/mcp/mcp-status-073c1634.mjs | 30761 +++++++++++++++ .../codex/scripts/check-service-fixture.mjs | 60 + .../codex/skills/service-readiness/SKILL.md | 33 + .../assets/readiness-report.md | 22 + .../references/status-policy.md | 22 + examples/mcp-app/artifact/portable/INSTALL.md | 19 + .../assets/evals/fixtures/status/result.json | 9 + .../mcp-app/artifact/portable/install.mjs | 80 + .../artifact/portable/mcp-apps/status.html | 154 + examples/mcp-app/artifact/portable/mcp.json | 1 + .../portable/mcp/mcp-status-073c1634.mjs | 30768 ++++++++++++++++ .../mcp-app/artifact/portable/plugin.json | 1 + .../scripts/check-service-fixture.mjs | 60 + .../skills/service-readiness/SKILL.md | 33 + .../assets/readiness-report.md | 22 + .../references/status-policy.md | 22 + .../artifact/agent-bundle.hooks.json | 1 + .../artifact/agent-bundle.manifest.json | 1 + .../claude/.claude-plugin/marketplace.json | 1 + .../claude/.claude-plugin/plugin.json | 1 + .../skills-starter/artifact/claude/INSTALL.md | 18 + .../claude/skills/dependency-upgrade/SKILL.md | 33 + .../dependency-upgrade/assets/upgrade-plan.md | 21 + .../references/compatibility-checklist.md | 9 + .../claude/skills/incident-triage/SKILL.md | 34 + .../incident-triage/assets/incident-update.md | 9 + .../references/triage-runbook.md | 9 + .../claude/skills/release-review/SKILL.md | 34 + .../release-review/assets/report-template.md | 22 + .../release-review/references/checklist.md | 8 + .../references/release-policy.md | 22 + .../codex/.agents/plugins/marketplace.json | 1 + .../artifact/codex/.codex-plugin/plugin.json | 1 + .../skills-starter/artifact/codex/INSTALL.md | 16 + .../codex/skills/dependency-upgrade/SKILL.md | 33 + .../dependency-upgrade/assets/upgrade-plan.md | 21 + .../references/compatibility-checklist.md | 9 + .../codex/skills/incident-triage/SKILL.md | 34 + .../incident-triage/assets/incident-update.md | 9 + .../references/triage-runbook.md | 9 + .../codex/skills/release-review/SKILL.md | 34 + .../release-review/assets/report-template.md | 22 + .../release-review/references/checklist.md | 8 + .../references/release-policy.md | 22 + .../artifact/portable/INSTALL.md | 19 + .../artifact/portable/install.mjs | 80 + .../artifact/portable/plugin.json | 1 + .../skills/dependency-upgrade/SKILL.md | 33 + .../dependency-upgrade/assets/upgrade-plan.md | 21 + .../references/compatibility-checklist.md | 9 + .../portable/skills/incident-triage/SKILL.md | 34 + .../incident-triage/assets/incident-update.md | 9 + .../references/triage-runbook.md | 9 + .../portable/skills/release-review/SKILL.md | 34 + .../release-review/assets/report-template.md | 22 + .../release-review/references/checklist.md | 8 + .../references/release-policy.md | 22 + packages/agent-bundle/src/test/registry.ts | 7 +- packages/agent-bundle/src/test/render.ts | 71 +- .../tests/projection/providers.test.ts | 15 +- 108 files changed, 95307 insertions(+), 21 deletions(-) create mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.hooks.json create mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.manifest.json create mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json create mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json create mode 100644 examples/hooks-and-scripts/artifact/claude/INSTALL.md create mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json create mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json create mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/hooks.json create mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs create mode 100644 examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json create mode 100644 examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json create mode 100644 examples/hooks-and-scripts/artifact/codex/INSTALL.md create mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json create mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json create mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/hooks.json create mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs create mode 100644 examples/hooks-and-scripts/artifact/portable/INSTALL.md create mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json create mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json create mode 100644 examples/hooks-and-scripts/artifact/portable/install.mjs create mode 100644 examples/hooks-and-scripts/artifact/portable/plugin.json create mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs create mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs create mode 100644 examples/mcp-app/artifact/agent-bundle.hooks.json create mode 100644 examples/mcp-app/artifact/agent-bundle.manifest.json create mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json create mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/plugin.json create mode 100644 examples/mcp-app/artifact/claude/.mcp.json create mode 100644 examples/mcp-app/artifact/claude/INSTALL.md create mode 100644 examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json create mode 100644 examples/mcp-app/artifact/claude/hooks/hooks.json create mode 100644 examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs create mode 100644 examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs create mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md create mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md create mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md create mode 100644 examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json create mode 100644 examples/mcp-app/artifact/codex/.codex-plugin/plugin.json create mode 100644 examples/mcp-app/artifact/codex/.mcp.json create mode 100644 examples/mcp-app/artifact/codex/INSTALL.md create mode 100644 examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json create mode 100644 examples/mcp-app/artifact/codex/hooks/hooks.json create mode 100644 examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs create mode 100644 examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs create mode 100644 examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs create mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md create mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md create mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md create mode 100644 examples/mcp-app/artifact/portable/INSTALL.md create mode 100644 examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json create mode 100644 examples/mcp-app/artifact/portable/install.mjs create mode 100644 examples/mcp-app/artifact/portable/mcp-apps/status.html create mode 100644 examples/mcp-app/artifact/portable/mcp.json create mode 100644 examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs create mode 100644 examples/mcp-app/artifact/portable/plugin.json create mode 100644 examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs create mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md create mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md create mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md create mode 100644 examples/skills-starter/artifact/agent-bundle.hooks.json create mode 100644 examples/skills-starter/artifact/agent-bundle.manifest.json create mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json create mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/plugin.json create mode 100644 examples/skills-starter/artifact/claude/INSTALL.md create mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md create mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md create mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md create mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md create mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md create mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/SKILL.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md create mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md create mode 100644 examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json create mode 100644 examples/skills-starter/artifact/codex/.codex-plugin/plugin.json create mode 100644 examples/skills-starter/artifact/codex/INSTALL.md create mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md create mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md create mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md create mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md create mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md create mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/SKILL.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md create mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md create mode 100644 examples/skills-starter/artifact/portable/INSTALL.md create mode 100644 examples/skills-starter/artifact/portable/install.mjs create mode 100644 examples/skills-starter/artifact/portable/plugin.json create mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md create mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md create mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md create mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md create mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md create mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/SKILL.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md create mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md diff --git a/.changeset/test-harness-conventional-providers.md b/.changeset/test-harness-conventional-providers.md index c4a50820f..aad845ed4 100644 --- a/.changeset/test-harness-conventional-providers.md +++ b/.changeset/test-harness-conventional-providers.md @@ -2,4 +2,4 @@ "agent-bundle": patch --- -The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity. Passing `context.providers` opts out and mounts the explicit map verbatim. The test manifest gains `providers`, the generated Rstest setup registers provider loaders, and the provider execution contract shared by the generated scopes and the harness lives in one module. +The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity. Passing `context.providers` opts out and mounts the explicit map verbatim. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. diff --git a/examples/audiobook-curator/tests/route-unit/context.test.ts b/examples/audiobook-curator/tests/route-unit/context.test.ts index af9abfeaf..87ff71b0b 100644 --- a/examples/audiobook-curator/tests/route-unit/context.test.ts +++ b/examples/audiobook-curator/tests/route-unit/context.test.ts @@ -38,7 +38,10 @@ it('renders the catalog from injected library context with its contents envelope }); it('renders an honest degraded catalog when library context is absent', async () => { + // The harness mounts `src/providers/library.ts` automatically, so the + // degraded path needs an explicit empty provider map to keep it absent. const rendered = await renderRoute('resource:curator/catalog', { + context: { providers: {} }, input: { uri: 'audiobook-curator://catalog' }, }); const value = rendered.document.value as { diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json b/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json new file mode 100644 index 000000000..c41cd4504 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json @@ -0,0 +1 @@ +{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json b/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json new file mode 100644 index 000000000..631297a39 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json @@ -0,0 +1 @@ +{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":287,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"f4dff087eb3c84f2b6e4ffeb632a3df21a631b70ad0328811dbaeabd8e29c043","sourceInputs":["agent-bundle.config.ts"]},{"bytes":182,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"2fa2d83fbdca7ab515bbd11c1cc2dffafedeabc2dc9cd647fb9646c057b31d54","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"claude/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"claude/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":11992,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"2faef48e3de116eea8e58c6e0d7f6cbfe4a98726fdcd6cc94f3ec5c5234c08ed","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":442,"kind":"generated","path":"claude/INSTALL.md","sha256":"0ca977cebb541b89cb7ef9cc47ed66dde2617f8c2beb5a697740ebfc2e4e0a14","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2089,"kind":"bundle","path":"claude/scripts/verify-release.mjs","sha256":"a9c836d6c1d878fd561788d2e6dab944f494e2aad25de0514a877246f1ba0854","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":264,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"eef1222beca7c354075e8da61d0fc50d68180b87da4f884890886868b6b40b89","sourceInputs":["agent-bundle.config.ts"]},{"bytes":534,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"e20e3a461fe89d8148d1aa53e729605316a6770215f86ec01c08ce7eaa672708","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"codex/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"codex/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12115,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"f786240293d08a5f3b8c7c3778b67acd5b03a39fbd753c1ef56e30007b416838","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":330,"kind":"generated","path":"codex/INSTALL.md","sha256":"b36d9e71a3d9e39947164524196269ba4084a28f6595558548d5f2639fb171ef","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2089,"kind":"bundle","path":"codex/scripts/verify-release.mjs","sha256":"a9c836d6c1d878fd561788d2e6dab944f494e2aad25de0514a877246f1ba0854","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":412,"kind":"copy","path":"portable/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"portable/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":667,"kind":"generated","path":"portable/INSTALL.md","sha256":"9fca655cfae6999fdac7a6562b003dff2353231f936b65791c7859cf7437b5b1","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3311,"kind":"generated","path":"portable/install.mjs","sha256":"3d5bab7f4f63582ed41027cbdd58122cf8aa04436647400639876c264751447f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":186,"kind":"generated","path":"portable/plugin.json","sha256":"7960fb9bcfd13c8bfbf113ac8b742d45f341df6fedf1c91525c421b10f63ad1e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1446,"kind":"bundle","path":"portable/scripts/detect-risk.mjs","sha256":"4d6fcf62f9bca98dd46b02628a745df3a38438aa03039b61758722762e3e691e","sourceInputs":["agent-bundle.config.ts","src/scripts/detect-risk.ts"]},{"bytes":2089,"kind":"bundle","path":"portable/scripts/verify-release.mjs","sha256":"a9c836d6c1d878fd561788d2e6dab944f494e2aad25de0514a877246f1ba0854","sourceInputs":["src/scripts/verify-release.ts"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c","configPath":"agent-bundle.config.ts","modelDigest":"c9c2a9a138a4736257fd35f0108d5b702cfd532efee090e77c33bb6b91028b5e","packageName":"@agent-bundle-example/hooks-and-scripts","revision":"5ad60dd354b14a6236614519d6c0880685cfa4878580de76228b0042ac0d036d","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c"},{"executable":false,"path":"package.json","sha256":"f34dac2a9133c3775239a0df45afc301bb257f3e628551ac6c12aad787841af6"},{"executable":false,"path":"README.md","sha256":"a22188781290ce67939e8dd339bc75b6dd520ded36a02de0b8a161d3a776afa1"},{"executable":false,"path":"release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77"},{"executable":false,"path":"release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"a5cda975fd148cf904b3c0cc5b0a860061ed89acd3704d54427c1313f23668e8"},{"executable":false,"path":"src/scripts/detect-risk.ts","sha256":"3b1d88c26219a410b6b23c019632fa8330ba5421d9294abbe9fc3f5300720370"},{"executable":false,"path":"src/scripts/verify-release.ts","sha256":"af661a44e63f38726d237df8821426884f64386f1e0a9f5c8c369932eac341c3"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.7.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"1d43c5ed19de401fb7455c5912e4c21113f6e387aef4c28d2eca121f7554c4e8"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"986bcafa6ef46f9dc4558f05781f53400b3d75533a075068184ba8d43670d4ec"}]},{"adapterRevision":"1.5.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json new file mode 100644 index 000000000..2cae8a879 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts-marketplace","owner":{"name":"hooks-and-scripts"},"plugins":[{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","source":"./","version":"1.0.0"}]} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json new file mode 100644 index 000000000..38dc8d3b1 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/claude/INSTALL.md b/examples/hooks-and-scripts/artifact/claude/INSTALL.md new file mode 100644 index 000000000..ea76a1f93 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/INSTALL.md @@ -0,0 +1,18 @@ +# Install hooks-and-scripts + +Hook simulation, script traces, logs, and recovery. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Claude Code + +Claude Code installs this bundle through its local marketplace contract: + +```sh +claude plugin marketplace add ./ +claude plugin install hooks-and-scripts@hooks-and-scripts-marketplace --scope user +``` + +Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json new file mode 100644 index 000000000..819d86560 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json @@ -0,0 +1,21 @@ +{ + "version": "2.4.0", + "changelog": "CHANGELOG.md#2.4.0", + "artifacts": [ + { + "name": "package", + "path": "dist/agent-bundle-2.4.0.tgz", + "status": "ready" + }, + { + "name": "checksums", + "path": "dist/agent-bundle-2.4.0.sha256", + "status": "ready" + }, + { + "name": "sbom", + "path": "dist/agent-bundle-2.4.0.sbom.json", + "status": "ready" + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json new file mode 100644 index 000000000..2295bcc45 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json @@ -0,0 +1,16 @@ +{ + "risks": [ + { + "id": "REL-204", + "severity": "high", + "status": "open", + "summary": "Complete the final approval for the release notes before publishing." + }, + { + "id": "REL-198", + "severity": "medium", + "status": "mitigated", + "summary": "Package signing rehearsal is documented in the release runbook." + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json b/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json new file mode 100644 index 000000000..1afdaac5a --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..afc422ebd --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,251 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, + `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, + 'Run detect-risk to surface open high-severity release blockers before publishing.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "claude"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeClaudeNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeClaudeNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeClaudeNative; +const encodeNative = encodeClaudeNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && 0) {} + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { + hookSpecificOutput: { + additionalContext: result.additionalContext, + hookEventName: nativeEvent + } + }; + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ + additionalContext: nativeOutput.hookSpecificOutput.additionalContext, + outcome: "continue" + }); + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (false) {} + else requireString(input, "transcript_path"); + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (false) {} + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (false) {} + else requireString(input, "last_assistant_message"); +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs new file mode 100644 index 000000000..576751775 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs @@ -0,0 +1,54 @@ +import { readFile } from "node:fs/promises"; + + + + + +const requiredArtifacts = [ + 'package', + 'checksums', + 'sbom' +]; +const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); +const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); +const validationErrors = (manifest)=>{ + const errors = []; + if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { + errors.push('version must use major.minor.patch format'); + } + if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { + errors.push('changelog must identify the release notes'); + } + for (const name of requiredArtifacts){ + const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); + if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { + errors.push(`${name} artifact must have a ready path`); + } + } + return errors; +}; +const main = async ()=>{ + try { + const manifest = await readManifest(); + const errors = validationErrors(manifest); + if (errors.length > 0) { + process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); + return 1; + } + process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const verify_release_entry_main = main; +if (typeof verify_release_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/verify-release.ts"); +} +const code = await verify_release_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json b/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json new file mode 100644 index 000000000..16e053eae --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"hooks-and-scripts"},"name":"hooks-and-scripts-marketplace","plugins":[{"category":"Productivity","name":"hooks-and-scripts","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json b/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json new file mode 100644 index 000000000..eeee06783 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","interface":{"capabilities":["hooks"],"category":"Productivity","defaultPrompt":["Help me use hooks-and-scripts."],"developerName":"hooks-and-scripts","displayName":"hooks-and-scripts","longDescription":"Hook simulation, script traces, logs, and recovery.","shortDescription":"Hook simulation, script traces, logs, and recovery."},"name":"hooks-and-scripts","skills":"./skills/","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/codex/INSTALL.md b/examples/hooks-and-scripts/artifact/codex/INSTALL.md new file mode 100644 index 000000000..97ee12563 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/INSTALL.md @@ -0,0 +1,16 @@ +# Install hooks-and-scripts + +Hook simulation, script traces, logs, and recovery. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Codex + +Codex installs this bundle from its local marketplace snapshot: + +```sh +codex plugin marketplace add ./ +codex plugin add hooks-and-scripts@hooks-and-scripts-marketplace +``` diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json new file mode 100644 index 000000000..819d86560 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json @@ -0,0 +1,21 @@ +{ + "version": "2.4.0", + "changelog": "CHANGELOG.md#2.4.0", + "artifacts": [ + { + "name": "package", + "path": "dist/agent-bundle-2.4.0.tgz", + "status": "ready" + }, + { + "name": "checksums", + "path": "dist/agent-bundle-2.4.0.sha256", + "status": "ready" + }, + { + "name": "sbom", + "path": "dist/agent-bundle-2.4.0.sbom.json", + "status": "ready" + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json new file mode 100644 index 000000000..2295bcc45 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json @@ -0,0 +1,16 @@ +{ + "risks": [ + { + "id": "REL-204", + "severity": "high", + "status": "open", + "summary": "Complete the final approval for the release notes before publishing." + }, + { + "id": "REL-198", + "severity": "medium", + "status": "mitigated", + "summary": "Package signing rehearsal is documented in the release runbook." + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json b/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json new file mode 100644 index 000000000..eb4f61756 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..ba527da9c --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,254 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, + `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, + 'Run detect-risk to surface open high-severity release blockers before publishing.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "codex"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeCodexNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeCodexNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeCodexNative; +const encodeNative = encodeCodexNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (true) requireNullableString(input, "transcript_path"); + else {} + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (true) { + requireString(input, "turn_id"); + requireString(input, "model"); + requireString(input, "permission_mode"); + if (![ + "default", + "acceptEdits", + "plan", + "dontAsk", + "bypassPermissions" + ].includes(input.permission_mode)) fail("native permission_mode is invalid"); + } + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (true) requireNullableString(input, "last_assistant_message"); + else {} +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs new file mode 100644 index 000000000..576751775 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs @@ -0,0 +1,54 @@ +import { readFile } from "node:fs/promises"; + + + + + +const requiredArtifacts = [ + 'package', + 'checksums', + 'sbom' +]; +const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); +const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); +const validationErrors = (manifest)=>{ + const errors = []; + if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { + errors.push('version must use major.minor.patch format'); + } + if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { + errors.push('changelog must identify the release notes'); + } + for (const name of requiredArtifacts){ + const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); + if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { + errors.push(`${name} artifact must have a ready path`); + } + } + return errors; +}; +const main = async ()=>{ + try { + const manifest = await readManifest(); + const errors = validationErrors(manifest); + if (errors.length > 0) { + process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); + return 1; + } + process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const verify_release_entry_main = main; +if (typeof verify_release_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/verify-release.ts"); +} +const code = await verify_release_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/INSTALL.md b/examples/hooks-and-scripts/artifact/portable/INSTALL.md new file mode 100644 index 000000000..0c3c03165 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/INSTALL.md @@ -0,0 +1,19 @@ +# Install hooks-and-scripts + +Hook simulation, script traces, logs, and recovery. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Portable Agent Plugin + +Portable is a distribution profile, not a host runtime with one universal install location. +This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). +Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run +`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT +are also native clients. The bundled installer provides the Cursor local copy: + +```sh +node ./install.mjs +``` diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json new file mode 100644 index 000000000..819d86560 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json @@ -0,0 +1,21 @@ +{ + "version": "2.4.0", + "changelog": "CHANGELOG.md#2.4.0", + "artifacts": [ + { + "name": "package", + "path": "dist/agent-bundle-2.4.0.tgz", + "status": "ready" + }, + { + "name": "checksums", + "path": "dist/agent-bundle-2.4.0.sha256", + "status": "ready" + }, + { + "name": "sbom", + "path": "dist/agent-bundle-2.4.0.sbom.json", + "status": "ready" + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json new file mode 100644 index 000000000..2295bcc45 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json @@ -0,0 +1,16 @@ +{ + "risks": [ + { + "id": "REL-204", + "severity": "high", + "status": "open", + "summary": "Complete the final approval for the release notes before publishing." + }, + { + "id": "REL-198", + "severity": "medium", + "status": "mitigated", + "summary": "Package signing rehearsal is documented in the release runbook." + } + ] +} diff --git a/examples/hooks-and-scripts/artifact/portable/install.mjs b/examples/hooks-and-scripts/artifact/portable/install.mjs new file mode 100644 index 000000000..8873d4b6a --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/install.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto'; +import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const pluginName = "hooks-and-scripts"; +const pluginVersion = "1.0.0"; +const source = resolve(fileURLToPath(new URL('.', import.meta.url))); +const cursorRoot = join(homedir(), '.cursor'); +const installRoot = join(cursorRoot, 'plugins', 'local'); +const destination = join(installRoot, pluginName); + +const exists = async (path) => { + try { await lstat(path); return true; } + catch (error) { if (error?.code === 'ENOENT') return false; throw error; } +}; + +const treeHash = async (root, prefix = '') => { + const rootMetadata = await lstat(root); + if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { + throw new Error('Refusing unsupported filesystem entry ".".'); + } + const hash = createHash('sha256'); + const visit = async (relative) => { + const absolute = join(root, relative); + const metadata = await lstat(absolute); + if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { + throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); + } + if (metadata.isDirectory()) { + for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); + return; + } + hash.update(relative.replaceAll('\\', '/')); + hash.update('\0'); + hash.update(await readFile(absolute)); + hash.update('\0'); + }; + for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); + return hash.digest('hex'); +}; + +const installedVersion = async () => { + for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { + try { + const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); + if (typeof value.version === 'string') return value.version; + } catch (error) { if (error?.code !== 'ENOENT') throw error; } + } + return undefined; +}; + +if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { + throw new Error(`Cursor is not installed in ${cursorRoot}.`); +} +await mkdir(installRoot, { recursive: true }); +if (await exists(destination)) { + const currentVersion = await installedVersion(); + if (currentVersion !== undefined && currentVersion !== pluginVersion) { + throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); + } + if (source === destination || await treeHash(source) === await treeHash(destination)) { + console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); + process.exit(0); + } + throw new Error(`Refusing content collision at ${destination}.`); +} + +const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); +const stage = join(stageParent, 'bundle'); +try { + await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); + await treeHash(stage); + await rename(stage, destination); + console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); +} finally { + await rm(stageParent, { force: true, recursive: true }); +} diff --git a/examples/hooks-and-scripts/artifact/portable/plugin.json b/examples/hooks-and-scripts/artifact/portable/plugin.json new file mode 100644 index 000000000..2f19512e9 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/plugin.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs new file mode 100644 index 000000000..6d3a3e5fe --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs @@ -0,0 +1,35 @@ +import { readFile } from "node:fs/promises"; + + + + + +const registerPath = new URL('../assets/release/risk-register.json', import.meta.url); +const main = async ()=>{ + try { + const register = JSON.parse(await readFile(registerPath, 'utf8')); + if (!Array.isArray(register.risks)) throw new Error('risk register must contain a risks array'); + const blockers = register.risks.filter((risk)=>risk.status === 'open' && risk.severity === 'high'); + if (blockers.length === 0) { + process.stdout.write('No open high-severity release risks found.\n'); + return 0; + } + for (const risk of blockers){ + process.stderr.write(`${typeof risk.id === 'string' ? risk.id : 'UNIDENTIFIED'}: ${typeof risk.summary === 'string' ? risk.summary : 'Open high-severity release risk'}\n`); + } + return 2; + } catch (error) { + process.stderr.write(`Unable to detect release risks: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const detect_risk_entry_main = main; +if (typeof detect_risk_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/detect-risk.ts"); +} +const code = await detect_risk_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs new file mode 100644 index 000000000..576751775 --- /dev/null +++ b/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs @@ -0,0 +1,54 @@ +import { readFile } from "node:fs/promises"; + + + + + +const requiredArtifacts = [ + 'package', + 'checksums', + 'sbom' +]; +const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); +const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); +const validationErrors = (manifest)=>{ + const errors = []; + if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { + errors.push('version must use major.minor.patch format'); + } + if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { + errors.push('changelog must identify the release notes'); + } + for (const name of requiredArtifacts){ + const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); + if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { + errors.push(`${name} artifact must have a ready path`); + } + } + return errors; +}; +const main = async ()=>{ + try { + const manifest = await readManifest(); + const errors = validationErrors(manifest); + if (errors.length > 0) { + process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); + return 1; + } + process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const verify_release_entry_main = main; +if (typeof verify_release_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/verify-release.ts"); +} +const code = await verify_release_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/mcp-app/artifact/agent-bundle.hooks.json b/examples/mcp-app/artifact/agent-bundle.hooks.json new file mode 100644 index 000000000..c41cd4504 --- /dev/null +++ b/examples/mcp-app/artifact/agent-bundle.hooks.json @@ -0,0 +1 @@ +{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/mcp-app/artifact/agent-bundle.manifest.json b/examples/mcp-app/artifact/agent-bundle.manifest.json new file mode 100644 index 000000000..02714aba2 --- /dev/null +++ b/examples/mcp-app/artifact/agent-bundle.manifest.json @@ -0,0 +1 @@ +{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":353,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"e4cf51c12ad7b9c9c78c3ae09e1564bff251152d162cd562247e8f5dca5868a7","sourceInputs":["agent-bundle.config.ts"]},{"bytes":214,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"20bca77e21ea7fbb9ceb1c1fd0c06b7bd67216a20d8a9922fab5ad8f915e5604","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":180,"kind":"generated","path":"claude/.mcp.json","sha256":"f7d402486d6d2de1fbbf6d95183a7f16aaed23f1b4b625c4075e3a67d11458aa","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"claude/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":11989,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"8928c1304415af7a31d6462ce1fafb9ff6139bd6555b561b84759148589e23ba","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":472,"kind":"generated","path":"claude/INSTALL.md","sha256":"84f35da9c85137d58c7ea6e458c1794e3396d95e709a2dde0784014ca784bb1b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"claude/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2331,"kind":"bundle","path":"claude/scripts/check-service-fixture.mjs","sha256":"16cf8a97c4e57bca609029a008621e944ac122a0760180d246d415495feee8a0","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"claude/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"claude/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"claude/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":258,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"c8b0fe73ece00cbf09fed92e1011d2d5e28211c7e7f4dfa1fddf3fba4c462b0a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":674,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"8dd1d6259f076f8f62cd35bb7c466c3dec95aeb4433416f4e52202f56673c11e","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":152,"kind":"generated","path":"codex/.mcp.json","sha256":"62064b39f8cddd0db51b7aa25a688bbff3ae7621376be506ff5d5542b037c9de","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"codex/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12112,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"850177a3fd7d801a7ffeb69ea0b936cad3b0fe939d8db84438b39d22353d0442","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":360,"kind":"generated","path":"codex/INSTALL.md","sha256":"4efefa497a9acdd073703dfc3ff2c81cd5005cea0f777a204a275988193c907f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"codex/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2331,"kind":"bundle","path":"codex/scripts/check-service-fixture.mjs","sha256":"16cf8a97c4e57bca609029a008621e944ac122a0760180d246d415495feee8a0","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"codex/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"codex/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"codex/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":231,"kind":"copy","path":"portable/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":701,"kind":"generated","path":"portable/INSTALL.md","sha256":"be9540f5b8012f6a7963532282469fa34119537a7203237fb18fd0b09f1710e3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3309,"kind":"generated","path":"portable/install.mjs","sha256":"971868b98246361915db7b21461b3cb105cc02bc0c163b70acaef9d89d0f9d6b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":447791,"kind":"bundle","path":"portable/mcp-apps/status.html","sha256":"b201f81745e2b36afc11433bd6232e4ac4979b9759411c7794aaa69017f6345d","sourceInputs":["agent-bundle.config.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":242,"kind":"generated","path":"portable/mcp.json","sha256":"79461543b66617388e3ead6b60c90576ee9ed9be17d4e19e2febf58b872e05e3","sourceInputs":["src/mcp/status.ts"]},{"bytes":1674914,"kind":"bundle","path":"portable/mcp/mcp-status-073c1634.mjs","sha256":"7203edfea8a8186dd4e00f1d839d46d409fde1e2ff4ddd931c828dd4f98c4fec","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/mcp/status.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":220,"kind":"generated","path":"portable/plugin.json","sha256":"e0e8d291a995eece0fdaf1200e86cd06089c219f1c74cbc55241b89e93fa72f3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2331,"kind":"bundle","path":"portable/scripts/check-service-fixture.mjs","sha256":"16cf8a97c4e57bca609029a008621e944ac122a0760180d246d415495feee8a0","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"portable/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"portable/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"portable/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89","configPath":"agent-bundle.config.ts","modelDigest":"8551c2c0a6630de6e3366155442b9919259fbf3331245219ad6e6dc4549069b3","packageName":"@agent-bundle-example/mcp-app","revision":"07e4db3dc80d12117f1d19af19e37d77502c9da1637f9f02e730ced76d634647","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89"},{"executable":false,"path":"evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811"},{"executable":false,"path":"evals/graders/status-result.ts","sha256":"b846dd661ff5f9af9dd15df7a2208344c13c6153514c9435a585a0caa820ebaf"},{"executable":false,"path":"evals/status.eval.ts","sha256":"ad0f9f1e216aec4684b4b51e337387b893c978e827ae8c5edf2ea41dfdf82207"},{"executable":false,"path":"package.json","sha256":"c98a8326ac7b5e0a0af64b14c59052387237354fc7c37c99d9de844ca07e3cbd"},{"executable":false,"path":"README.md","sha256":"35e3f3656ce34c5ed1181917ecebc40d10ec3f121630ade7ff7db7093e2db6df"},{"executable":false,"path":"rstest.browser-app.config.ts","sha256":"e2de9384badc7c4fb6b89ea5b54ed85fd3cacbe9e31162555362d0c89a318557"},{"executable":false,"path":"src/compiler-status-contract.ts","sha256":"ff8484b2ae613abb1cf2f76c70f558733563228570df1c05485a3a04ebffcd59"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"b856621ec280ed94a8e1dfa0fe065a1ff4d41690ff07be9e148c01b1180fd346"},{"executable":false,"path":"src/mcp/status.ts","sha256":"9116902d7041d30b4c3fcb412b2d83a793975fdac9632648e07dfc85da2a73c1"},{"executable":false,"path":"src/scripts/check-service-fixture.ts","sha256":"32967d447487049c62af2195612ec6f2b5de630753ea2c20b473faf93e804fba"},{"executable":false,"path":"src/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b"},{"executable":false,"path":"src/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b"},{"executable":false,"path":"src/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3"},{"executable":false,"path":"tests/browser-app/status-panel.browser.test.ts","sha256":"a49e632decebd56db42214afc3f1cba8729c24b594935e4b2468e3a2d4ad6695"},{"executable":false,"path":"views/status-panel.html","sha256":"75018093566d7bfdf16dfffcc072d4983e0c2ecd5f40f592e27e571cb3e5a868"},{"executable":false,"path":"views/status-panel.ts","sha256":"3bd3017d4f4d730293b15f386c5949b390bc8bba1ed2c5fd861efed477afefc8"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.7.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"1d43c5ed19de401fb7455c5912e4c21113f6e387aef4c28d2eca121f7554c4e8"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"986bcafa6ef46f9dc4558f05781f53400b3d75533a075068184ba8d43670d4ec"}]},{"adapterRevision":"1.5.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json b/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json new file mode 100644 index 000000000..d24f68ca5 --- /dev/null +++ b/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example-marketplace","owner":{"name":"mcp-app-example"},"plugins":[{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","source":"./","version":"1.0.0"}]} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json b/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json new file mode 100644 index 000000000..3a3e7a43d --- /dev/null +++ b/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/claude/.mcp.json b/examples/mcp-app/artifact/claude/.mcp.json new file mode 100644 index 000000000..a8c317b72 --- /dev/null +++ b/examples/mcp-app/artifact/claude/.mcp.json @@ -0,0 +1 @@ +{"mcpServers":{"status":{"args":["${CLAUDE_PLUGIN_ROOT}/mcp/mcp-status-073c1634.mjs"],"command":"node","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${CLAUDE_PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/claude/INSTALL.md b/examples/mcp-app/artifact/claude/INSTALL.md new file mode 100644 index 000000000..b69cfdbf3 --- /dev/null +++ b/examples/mcp-app/artifact/claude/INSTALL.md @@ -0,0 +1,18 @@ +# Install mcp-app-example + +A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Claude Code + +Claude Code installs this bundle through its local marketplace contract: + +```sh +claude plugin marketplace add ./ +claude plugin install mcp-app-example@mcp-app-example-marketplace --scope user +``` + +Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json new file mode 100644 index 000000000..a765aa4b5 --- /dev/null +++ b/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json @@ -0,0 +1,9 @@ +{ + "service": "compiler", + "status": "healthy", + "summary": "Compiler service is ready for release.", + "checks": [ + { "label": "Availability", "status": "passing" }, + { "label": "Build queue", "status": "passing" } + ] +} diff --git a/examples/mcp-app/artifact/claude/hooks/hooks.json b/examples/mcp-app/artifact/claude/hooks/hooks.json new file mode 100644 index 000000000..1afdaac5a --- /dev/null +++ b/examples/mcp-app/artifact/claude/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..4b76f8870 --- /dev/null +++ b/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,251 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, + `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, + 'Use show-status for compiler or payments-api when live service evidence is needed.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "claude"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeClaudeNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeClaudeNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeClaudeNative; +const encodeNative = encodeClaudeNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && 0) {} + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { + hookSpecificOutput: { + additionalContext: result.additionalContext, + hookEventName: nativeEvent + } + }; + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ + additionalContext: nativeOutput.hookSpecificOutput.additionalContext, + outcome: "continue" + }); + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (false) {} + else requireString(input, "transcript_path"); + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (false) {} + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (false) {} + else requireString(input, "last_assistant_message"); +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs new file mode 100644 index 000000000..29189bf45 --- /dev/null +++ b/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs @@ -0,0 +1,30761 @@ +import node_process from "node:process"; + +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/mcp/status.ts +var status_namespaceObject = {}; +__webpack_require__.r(status_namespaceObject); +__webpack_require__.d(status_namespaceObject, { + createStatusServer: () => (createStatusServer), + "default": () => (mcp_status) }); + + +// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +var stdio_namespaceObject = {}; +__webpack_require__.r(stdio_namespaceObject); +__webpack_require__.d(stdio_namespaceObject, { + StdioServerTransport: () => (stdio_StdioServerTransport) }); + + +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion + +//#region ../core-internal/src/validators/dialects.ts +/** +* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). +*/ +const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); +const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); +const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); +const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); +/** +* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with +* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so +* wire-layer callers can consult it for documents whose dialect may be unsupported. +*/ +function declares2019Dialect($schema) { + return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); +} +/** +* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means +* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the +* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling +* provider's escape hatch in that message. +*/ +function declaredDialect(schema, remedy) { + if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; + const declared = schema.$schema.replace(/#$/, ""); + if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; + if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; + if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); +} + +//#endregion + +//# sourceMappingURL=dialects-DoSzNhcb.mjs.map + +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function toZod() { + return (schema) => schema; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function util_cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function util_esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function util_isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const util_allowsEval = /* @__PURE__*/ util_cached(() => { + // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. + if (globalConfig.jitless) { + return false; + } + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (util_isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (util_isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); +const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined", +]))); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; + }); +} +// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + // `for...in` skips symbols, so a symbol in the mask would select nothing + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + assignProp(newShape, key, currDef.shape[key]); + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values + const existingShape = schema._zod.def.shape; + for (const key of Reflect.ownKeys(shape)) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function merge(a, b) { + if (!b?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [], + }); + return clone(a, def); +} +function partial(Class, schema, mask, name = "partial") { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + else { + // the spread copies symbol keys; `for...in` would not reach them + for (const key of Reflect.ownKeys(oldShape)) { + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +function util_required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key of Reflect.ownKeys(oldShape)) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + }); + return clone(schema, def); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) { + (_a = issues[i]).schema ?? (_a.schema = inst); + } +} +function finalizeIssue(iss, ctx, config) { + var _a; + // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a = iss).schema ?? (_a.schema = iss.inst); + else + iss.schema = iss.inst; + } + // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; + const message = iss.message + ? iss.message + : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(schemaError?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"); + const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +const highSurrogate = /[\uD800-\uDBFF]/; +// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function util_issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class util_Class { + constructor(..._args) { } +} +////////// PROTOTYPE INSTALLERS ////////// +// +// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. +/** + * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. + * + * Call this from a `proto` initializer, which runs once per prototype — never per instance. + */ +function util_members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was + if (desc.get) + Object.defineProperty(proto, key, { ...desc, enumerable: false }); + // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` + else + defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function util_own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return util_own(inst, key, value, false); +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method + return this == null ? fn : util_own(this, key, fn.bind(this)); + }, + set(value) { + util_own(this, key, value); + }, + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. + return sentinel in proto ? undefined : proto; +} +// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. +let installing; +// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + return undefined; + }, +}; +/** + * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s + * constructor, computed from the internals object itself and cached there on + * first read. One accessor per constructor rather than one per instance. + */ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. + installing = undefined; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } + catch (err) { + // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + }, + }); +} +/** + * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own + * data property. One accessor per constructor rather than one per instance, because an own accessor + * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. + */ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. + const desc = { configurable: true, writable: true, enumerable, value: undefined }; + Object.defineProperty(this, key, desc); + // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + }, + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +var core_a; + +/** A special constant with type `never` */ +const NEVER = /*@__PURE__*/ Object.freeze({ + status: "aborted", +}); +/* Shared descriptor for installing `_zod`; defineProperty reads it + * synchronously, so reusing one object avoids a per-instance allocation. */ +const _zodDesc = { value: undefined, enumerable: false }; +// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error +let _E = "captureStackTrace" in Error ? Error : null; +// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } + catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } + finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, +/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ +proto, params) { + // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. + const zodProto = {}; + // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. + const initialized = protoMembers && new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } + finally { + // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. + _zodDesc.value = undefined; + } + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + util_members(target, protoMembers); + } + } + // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) + continue; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. + inst._zod.deferred = undefined; + } + // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function core_config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +class $ZodCyclicError extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +} +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +// Receivers prefix paths in place, so the cache and every hand-out need their own copies. +function cloneIssues(issues) { + return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack) { + const cached = recursive.get(inst); + if (cached !== undefined) + return cached; + // Relative to the walk in progress, so not cached. + if (stack.has(inst)) + return true; + stack.add(inst); + let result = false; + const check = (child) => { + if (!result && child?._zod && isRecursive(child, stack)) + result = true; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen + for (const key of Reflect.ownKeys(def.shape)) + check(def.shape[key]); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) + check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) + check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + // reading `_zod.innerType` resolves the getter once and caches it + case "lazy": + check(inst._zod.innerType); + break; + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + // a new built-in kind becomes a compile error here + kind; + // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code + for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) + continue; + const value = desc.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check(value); + else if (Array.isArray(value)) + for (const el of value) + check(el); + } + } + } + stack.delete(inst); + recursive.set(inst, result); + return result; +} +/** + * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. + * Exported for `z.compile`, which refuses to compile such a schema: cycle + * breaking is driven from here off state keyed on the parse context, and a + * generated fast path has no context to key on. + */ +function isRecursiveSchema(inst) { + return isRecursive(inst, new Set()); +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = new Map(); + state.buckets.set(inst, bucket); + } + return bucket; +} +// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. +let handoff; +// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. +const memoizer_open = []; +const memoizer_memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = undefined; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + memoizer_open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes + let lastCtx; + let lastBucket; + // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === undefined) { + isRecursiveInst = isRecursive(inst, new Set()); + if (!isRecursiveInst) { + // Nothing here can ever fire, so take it back out. + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + } + const input = payload.value; + if (input === null || typeof input !== "object") + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: new Map(), backEdges: undefined }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } + else { + // Still being parsed: its own checks cover it, so skip them here. + payload.memo = true; + state.backEdges ?? (state.backEdges = new Set()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = memoizer_open.length; + const result = base(payload, ctx); + handoff = undefined; + // A container that rejected its input outright allocated nothing. + const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; + // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memoizer_memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); +} + + +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?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)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. +const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const regexes_ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/; +const mac = (delimiter) => { + const escapedDelim = util.escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const regexes_base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; +const httpProtocol = /^https?$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 +const e164 = /^\+[1-9]\d{6,14}$/; +// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). +const creditCard = /^\d(?:[ -]?\d){11,18}$/; +const dateSource = `(?:(?:\\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])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because + * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it + * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function regexes_anchor(source) { + return new RegExp(`^${source}$`); +} +const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : args.seconds + ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function regexes_time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const opts = ["Z"]; + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const regexes_string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const regexes_boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const regexes_hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); +const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); +const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); +const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); +const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); +const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); + +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ +const _whenHasSize = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; +}; +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; +}; +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. + const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. + const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 + ? codePointLength(input) + : units; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 + ? codePointLength(input) + : units; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + // `String.prototype.includes(sub, position)` matches `sub` at `position` + // OR LATER, so the pattern must allow at least `position` leading chars + // (`{N,}`), not exactly `position` chars (`{N}`). + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +class Doc { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); + return factory(...Object.values(this.closed)); + } +} + + + +/* Computing the message eagerly is expensive (pretty-printed JSON of all + * issues), so defer it until first read. The accessor functions and + * descriptors are shared across instances to keep error construction + * cheap; the computed message is cached on the internals object. The + * setter preserves plain assignment semantics for consumers that + * overwrite `message`. */ +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true, +}; +const errors_zodDesc = { value: undefined, enumerable: false }; +const _issuesDesc = { value: undefined, enumerable: false }; +/* Prototypes that already carry the lazy `toString`. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const errors_initializer = (inst, def) => { + inst.name = "$ZodError"; + errors_zodDesc.value = inst._zod; + Object.defineProperty(inst, "_zod", errors_zodDesc); + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + // Clear the shared slots; a retained `value` pins the last error's issues. + errors_zodDesc.value = undefined; + _issuesDesc.value = undefined; + Object.defineProperty(inst, "message", _messageDesc); + /* `toString` lives as a non-enumerable lazy getter on the shared + * prototype; on first access it caches a per-instance closure so + * detached usage still works. */ + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + }, + }); + } +}; +const $ZodError = $constructor("$ZodError", errors_initializer); +const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { + Parent: Error, +}); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member + * ("toString", "constructor") would otherwise read through to the prototype, and assigning + * "__proto__" would hit the setter instead of creating a key. */ +function errors_node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } + else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue)); + i++; + continue; + } + // A path element may collide with an inherited property name such as + // "__proto__" or "constructor". Truthiness checks read the prototype + // (so no node is created, then ._errors.push throws), and bracket + // assignment of "__proto__" hits the setter instead of creating an + // own key. Guard the read with hasOwnProperty and create the node + // with defineProperty so any path element becomes a real own key. + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + const node = curr[el]; + if (terminal) { + node._errors.push(mapper(issue)); + } + curr = node; + i++; + } + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + // el may collide with an inherited property name ("__proto__", + // "constructor", ...); ??= reads the prototype so the node is never + // created and curr.errors.push throws. Guard with hasOwnProperty and + // create the node with defineProperty so "__proto__" becomes a real + // own key rather than invoking the prototype setter. + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + + + + +// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +const parse_parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); +const parse_parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +// registry mirrors of the compiler's sentinels, so this module never imports the compiler +const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); +const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); +// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. +const parse_validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== undefined && validator(value) !== COMPILE_INVALID) + return true; + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } + else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + return result.issues.length === 0; +} +// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw +const parse_validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +const parse_encode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const encode = /* @__PURE__*/ parse_encode($ZodRealError); +const parse_decode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decode = /* @__PURE__*/ parse_decode($ZodRealError); +const parse_encodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); + }; + return fn; +}; +const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); +const parse_decodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); + +const versions_version = { + major: 4, + minor: 5, + patch: 4, +}; + + + + + + + + +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const defChecks = inst._zod.def.checks; + // if inst is itself a checks.$ZodCheck, run it as a check + const checks = inst._zod.traits.has("$ZodCheck") + ? [inst, ...(defChecks ?? [])] + : defChecks?.length + ? [...defChecks] + : []; + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) + return payload; + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; +function standardProps(inst) { + return { + validate: (value) => { + try { + return toStandardResult(safeParse(inst, value)); + } + catch (_) { + return safeParseAsync(inst, value).then(toStandardResult); + } + }, + vendor: "zod", + version: 1, + }; +} + +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } + else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL constructor rejected the input. */ +const URL_UNPARSEABLE = 2; +/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ +function parseURLObject(trimmed, def) { + // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + // @ts-ignore + return new URL(trimmed); + } + catch { + return URL_UNPARSEABLE; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + const url = parseURLObject(trimmed, def); + if (url === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + if (def.protocol && !urlProtocolOk(url, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + // Set the output value based on normalize flag + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema + if (def.local || def.precision === -1) { + inst._zod.bag.laxFormat = true; + inst._zod.onattach.push((s) => { + s._zod.bag.laxFormat = true; + }); + } +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes_date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes_time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + try { + // @ts-ignore + new URL(`http://[${value}]`); + return true; + } + catch { + return false; + } +} +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes_ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + // atob ignores whitespace, so reject it up front. + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes_base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodCreditCard ////////////////////////////// +const CC_SANITIZE = /[- ]/g; +/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ +function isLuhnAlgo(digits) { + let length = digits.length; + let bit = 1; + let sum = 0; + while (length) { + const value = +digits[--length]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input) { + if (!regexes.creditCard.test(input)) + return false; + return isLuhnAlgo(input.replace(CC_SANITIZE, "")); +} +const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { + // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. + def.pattern ?? (def.pattern = regexes.creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? String(input) + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } + if (result.issues.length) { + // For optional-in/out schemas, ignore errors on absent keys. + if (optin !== undefined && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && optin === undefined) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [key], + }); + } + return; + } + if (result.value === undefined) { + if (isPresent) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +// one shared instance; a fresh [] per schema cost 56 bytes retained +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + // aliases `keys` when there are no symbols, so a string-only shape keeps one array + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + for (const key in input) { + // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. + if (keySet.has(key)) + continue; + // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. +const propShapes = new WeakMap(); +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + // const sh = def.shape; + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + propShapes.set(def, sh); + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh, + }); + propShapes.set(def, newSh); + return newSh; + }, + }); + } + const _normalized = util_cached(() => normalizeDef(def)); + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, new Set()); + } + for (const v of field.values) + propValues[key].add(v); + // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. + if (field.optin !== undefined) + propValues[key].add(undefined); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value; + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + for (const key of value.allKeys) { + if (key === "__proto__") + continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = util_cached(() => normalizeDef(def)); + const memo = globalConfig.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope + const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + // Prefixes in place, like util.prefixIssues does for every interpreted path. + const prefixStr = (id, k) => ` + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== undefined; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } + else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + } + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${id}.value === undefined) { + if (${isPresent}) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone + return doc.compile(); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") + ? "defaulted" + : zod.def.options.some((o) => o._zod.optin !== undefined) + ? "optional" + : undefined); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; + return final; + } + if (matches.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + matches, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}))); +/** Returns the option of `union` whose discriminator claims `value`. */ +function getDiscriminatedOption(union, value) { + const internals = union._zod; + let map = internals.bag.optionsMap; + if (!map) { + map = new Map(); + const { options, discriminator } = internals.def; + for (const option of options) { + // First declaration wins, matching the order the parse path resolves a duplicate in. + for (const v of option._zod.propValues?.[discriminator] ?? []) + if (!map.has(v)) + map.set(v, option); + } + internals.bag.optionsMap = map; + } + return map.get(value); +} +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazyInternal(inst, "propValues", (zod) => { + const propValues = {}; + for (const option of zod.def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, new Set()); + } + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. + def.options.forEach((option, i) => { + const propShape = propShapes.get(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); + } + }); + const disc = util_cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + // Fall back to union matching when the fast discriminator path fails: + // - explicitly enabled via unionFallback, or + // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") + continue; + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. + const unrecKeys = new Map(); + let unrecIssue; + const keyIssues = new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } + else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; + } + else { + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); + } + for (const iss of right.issues) { + if (!collect(iss, "r")) + result.issues.push(iss); + } + // Report only keys rejected by BOTH sides + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } + } + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + if (aborted(result)) + return result; + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array", + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array", + }); + } + } + // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } + else { + itemResults[i] = r; + } + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}))); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. + const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...util.prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + // Drop trailing slots that produced `undefined` for absent input + // (the array analog of an absent optional key on an object). The + // `i >= input.length` floor is critical: an explicit `undefined` + // *inside* the input must be preserved even when the schema is + // optional-out (e.g. `z.string().or(z.undefined())` accepting an + // explicit undefined value). + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { + final.value.length = i; + } + else { + break; + } + } + return final; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + // A declared __proto__ is stripped but is not an unrecognized key. + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + if (def.mode === "loose") { + // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into + if (key === "__proto__") + continue; + payload.value[key] = input[key]; + } + else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. + let unrecognized; + // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + } + continue; + } + // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + const values = new Set(def.values); + inst._zod.values = values; + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(def.values.length + ? `^(${def.values + .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) + .join("|")})$` + : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. + payload.value = result.issues.length ? undefined : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + defineLazyInternal(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? new Set([...values, undefined]) : undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. + if (def.innerType._zod.optin !== "defaulted") + return payload; + // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + // Call parent init - inherits optin/optout = "optional" + $ZodOptional.init(inst, def); + // Override values/pattern to NOT add undefined + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + // Override parse to just delegate (no undefined handling) + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; + }); + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new core.$ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. + if (result.memo) + payload.memo = true; + return payload; + } + // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + }, + input: payload.value, + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) { + return result.then((result) => handleCatchResult(payload, result, def, ctx)); + } + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}))); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. + if (!payload.memo) + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. + Object.defineProperty(inst, "_def", { value: def }); + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. + return Object.defineProperty(function (...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return Object.defineProperty(async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. + defineLazy(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } +} + +var registries_a; +const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); +const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registries_registry() { + return new $ZodRegistry(); +} +(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + + + + + +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link _cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _creditCard(Class, params) { + return new Class({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +const TimePrecision = (/* unused pure expression or super */ null && ({ + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +})); +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ + type: "any", + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return _gt(0, params); +} +// negative +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return _lt(0, params); +} +// nonpositive +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum, + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length, + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes, + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _properties(shape) { + return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +// @__NO_SIDE_EFFECTS__ +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +// @__NO_SIDE_EFFECTS__ +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); + }, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params), + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function api_meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = util.normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? schemas.$ZodCodec; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + codec._zod.bag.truthy = truthyArray; + codec._zod.bag.falsy = falsyArray; + codec._zod.bag.case = params.case ?? "insensitive"; + return codec; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = util.normalizeParams(_params); + const def = { + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + + + +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + sharedDefsExtractedFor: undefined, + sharedEmitDoneFor: undefined, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? undefined, + }; +} +/** + * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws + * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a + * custom JSON Schema was written into `json`, in which case the caller must not write its own. + */ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" + ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) + : ctx.unrepresentable; + if (result === "any") + return false; + if (result === undefined || result === "throw") + throw new Error(message); + Object.assign(json, result); + return true; +} +function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = undefined; + ctx.sharedEmitDoneFor = undefined; + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + // Also set ref if processor didn't (for inheritance) + if (!result.ref) + result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && "_prefault" in result.schema) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; + // Track ids to detect duplicates across different schemas + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } + // self-contained schema + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; + }; + // stored cached version in `def` property remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) + return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types.includes(member)) + types.push(member); + } + } + delete schema.anyOf; + // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, + * an annotation like `description` — makes a member unfoldable, so a constraint this does not + * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + // A boolean subschema is legal JSON Schema and carries no keywords to fold. + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required = new Set(); + for (const object of objects) { + for (const key in object.properties) { + // `in` would report a `__proto__` key as already present via the prototype chain and skip it. + if (Object.prototype.hasOwnProperty.call(properties, key)) + continue; + // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === undefined) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); + } + const merged = parts.length === 1 + ? parts[0] + : (foldObjects(parts) ?? { allOf: parts }); + assignProp(properties, key, merged); + } + for (const key of object.required ?? []) + required.add(key); + } + const folded = { type: "object", properties }; + if (required.size) + folded.required = [...required]; + // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. + if (objects.every((object) => object.additionalProperties === false)) { + folded.additionalProperties = false; + } + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two + * closed object members reject each other's keys and the schema validates nothing. Zod's parser + * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when + * *every* side rejects it — so the emitted schema has to pool them too, and folding the members + * into one object is the encoding that says so on every target. + * + * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` + * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it + * keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. + for (const key of FOLDABLE_KEYS) + if (key in json) + return; + // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) + return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten refs - inherit properties from parent schemas + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + // already processed + if (seen.ref === null) + return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; // prevent infinite recursion + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + // merge referenced schema into current + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + // older drafts can't combine $ref with other properties + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + assignProps(schema, refSchema); + } + // restore child's own properties (child wins) + assignProps(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + // For parent chain, child is a refinement - remove parent-only properties + if (isParentRef) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema[key]; + } + } + } + // When ref was extracted to $defs, remove properties that match the definition + if (refSchema.$ref && refSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { + delete schema[key]; + } + } + } + } + // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + // Ensure parent is processed first so its def has inherited properties + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + // De-duplicate with parent's definition + if (parentSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema[key]; + } + } + } + } + } + // execute overrides + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. + if (ctx.intersections.length) { + const carriers = new Map(); + for (const seen of ctx.seen.values()) { + for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json); + else + carriers.set(allOf, [json]); + } + } + for (const allOf of ctx.intersections) { + for (const json of carriers.get(allOf) ?? []) + foldIntersection(json); + } + } + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs + assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); + // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== undefined && result.id === rootMetaId) + delete result.id; + // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } + } + } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault" || + def.type === "catch") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + + + + +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids + if (format === "time" || laxFormat) { + delete json.format; + } + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns]; + if (patternList.length === 1) + json.pattern = patternList[0].source; + else if (patternList.length > 1) { + json.allOf = [ + ...patternList.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + // when both minimum and exclusiveMinimum exist, pick the more restrictive one + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + else if (typeof minimum === "number") { + json.minimum = minimum; + } + if (exMax) { + if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + else if (typeof maximum === "number") { + json.maximum = maximum; + } + if (typeof multipleOf === "number") { + // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. + if (Number.isFinite(multipleOf) && multipleOf !== 0) + json.multipleOf = Math.abs(multipleOf); + else + handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); +}; +const symbolProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); +}; +const voidProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + // an empty enum accepts nothing, same as z.never() + if (values.length === 0) { + json.not = {}; + return; + } + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // a literal with no values accepts nothing, same as z.never() + if (def.values.length === 0) { + json.not = {}; + return; + } + const vals = []; + for (const val of def.values) { + if (val === undefined) { + // a custom schema replaces the whole literal, so there is nothing left to accumulate + if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; + // otherwise do not add to vals + } + else if (typeof val === "bigint") { + if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } + else { + Object.assign(_json, file); // shared props at root + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs + } + } + else { + Object.assign(_json, file); + } +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const functionProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const mapProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); +}; +const setProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { + ...params, + path: [...params.path, "items"], + }); +}; +// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an +// absent key, but their declared input type stays required. An input JSON Schema describes the +// declared type, so resolve past them to the schema that actually carries the optionality. +// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see +// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && + handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } + json.type = "object"; + json.properties = {}; + for (const key in shape) { + // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into + assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + })); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const field = def.shape[key]; + if (ctx.io === "input") { + return inputOptin(field) === undefined; + } + else { + return field._zod.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. + ctx.intersections.push(allOf); +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; + if (!optional) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (isClosed) { + json.items = false; + } + else if (rest) { + json.items = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else { + json.items = prefixItems; + if (isClosed) { + json.additionalItems = false; + } + else if (rest) { + json.additionalItems = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + // explicit user-defined length checks take precedence + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the + * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key + * behind a wrapper only carries its own `type` before then, and a union key only has its branches. + * + * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather + * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this + * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` + * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema + * outright. */ +function stringifyKeyNames(bySchema, json, visited) { + // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. + if (json.$ref) { + // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again + if (visited.has(json)) + return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) + return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` + if (mapped.some((branch, i) => branch !== branches[i])) + json = { ...json, [keyword]: mapped }; + } + // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + // a heterogeneous key carries no type at all, so its numeric members are caught here instead + const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); + if (!numericType && !values?.some((v) => typeof v === "number")) + return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) + rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + // a heterogeneous key keeps its absent type: the stringified members already say what a key may be + if (!numericType) + return rest; + rest.type = "string"; + if (!values) + rest.pattern = (types.includes("number") ? number : integer).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = new WeakMap(); +function rewriteKeyNames(ctx) { + // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. + const bySchema = new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + // Use patternProperties for looseRecord with regex patterns + const valueSchema = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"], + }); + json.patternProperties = {}; + for (const pattern of patterns) { + assignProp(json.patternProperties, pattern.source, valueSchema); + } + } + else { + // Default behavior: use propertyNames + additionalProperties + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + // Add required for keys with discrete values (enum, literal, etc.) + const keyValues = keyType._zod.values; + // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json.required = validKeyValues.map(String); + } + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. + * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other + * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + assignProp(schemas, key, finalize(ctx, schema)); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + + +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + credit_card: "credit card number", + jwt: "JWT", + template_literal: "input", + }; + // type names: missing keys = do not translate (use raw value via ?? fallback) + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN", + // All other type names omitted - they fall back to raw values via ?? operator + }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { + return String(input); + } + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": { + const expected = getTypeName(issue.expected); + const receivedType = parsedType(issue.input); + const received = getTypeName(receivedType, issue.input); + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { + const opts = issue.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + if (issue.inclusive === false) { + return "Invalid input: more than one option matched"; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* export default */ function en() { + return { + localeError: en_error(), + }; +} + + + + +/* Prototypes that already carry the lazy helper methods. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +/* Helper methods live as non-enumerable lazy getters on the shared + * prototype instead of own properties on every instance. On first + * access the getter allocates the per-instance closure and caches it + * as a non-enumerable own property, so detached usage still works and + * the allocation only happens for methods actually touched. */ +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + }, + }); +} +const classic_errors_initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + }, + }); +}; +const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); +const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + + + +const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); +const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); +const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// Codec functions +const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); +const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); +const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); +const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); +const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + + + + + + + + +// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + core_config(en()); +} +// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + core_config({ memoizer: memoizer() }); +} +const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { + checks: [ + ...(def.checks ?? []), + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return schemas_optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return schemas_optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return schemas_array(this); + }, + or(arg) { + return schemas_union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return schemas_default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return schemas_catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(undefined).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output"), + }, + }); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, + parse: function _parse(data, params) { + return classic_parse_parse(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return parse_safeParse(this, data, params); + }, + async safeParseAsync(data, params) { + return parse_safeParseAsync(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_own(this, "spa", value); + }, + encode: function _encode(data, params) { + return classic_parse_encode(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return classic_parse_decode(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return parse_safeEncode(this, data, params); + }, + safeDecode(data, params) { + return parse_safeDecode(this, data, params); + }, + async safeEncodeAsync(data, params) { + return parse_safeEncodeAsync(this, data, params); + }, + async safeDecodeAsync(data, params) { + return parse_safeDecodeAsync(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + }, +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; +}, { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + }, +}); +const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(api_emoji(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(schemas_ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(schemas_ZodISODuration, params)); + }, +}); +function schemas_string(params) { + return _string(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_email(params) { + return _email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_guid(params) { + return core._guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_uuid(params) { + return core._uuid(ZodUUID, params); +} +function uuidv4(params) { + return core._uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return core._uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function uuidv7(params) { + return core._uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return core._url(ZodURL, { + protocol: core.regexes.httpProtocol, + hostname: core.regexes.domain, + ...util.normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_emoji(params) { + return core._emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_nanoid(params) { + return core._nanoid(ZodNanoID, params); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** + * Validates a CUID v1 string. + * + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. + * See https://github.com/paralleldrive/cuid. + */ +function schemas_cuid(params) { + return core._cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid2(params) { + return core._cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ulid(params) { + return core._ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_xid(params) { + return core._xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ksuid(params) { + return core._ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv4(params) { + return core._ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_mac(params) { + return core._mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv6(params) { + return core._ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv4(params) { + return core._cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv6(params) { + return core._cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64(params) { + return core._base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64url(params) { + return core._base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_e164(params) { + return core._e164(ZodE164, params); +} +const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { + core.$ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_creditCard(params) { + return core._creditCard(ZodCreditCard, params); +} +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return core._jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function stringFormat(format, fnOrRegex, _params = {}) { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function schemas_hostname(_params) { + return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); +} +function schemas_hex(_params) { + return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); +} +function schemas_hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = core.regexes[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return core._stringFormat(ZodCustomStringFormat, format, regex, params); +} +const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}, { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(schemas_int(params)); + }, + safe(params) { + return this.check(schemas_int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + }, +}); +function schemas_number(params) { + return _number(ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function schemas_int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return core._float32(ZodNumberFormat, params); +} +function float64(params) { + return core._float64(ZodNumberFormat, params); +} +function int32(params) { + return core._int32(ZodNumberFormat, params); +} +function uint32(params) { + return core._uint32(ZodNumberFormat, params); +} +const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function schemas_boolean(params) { + return _boolean(ZodBoolean, params); +} +const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}, { + gte(value, params) { + return this.check(checks.gte(value, params)); + }, + min(value, params) { + return this.check(checks.gte(value, params)); + }, + gt(value, params) { + return this.check(checks.gt(value, params)); + }, + lt(value, params) { + return this.check(checks.lt(value, params)); + }, + lte(value, params) { + return this.check(checks.lte(value, params)); + }, + max(value, params) { + return this.check(checks.lte(value, params)); + }, + positive(params) { + return this.check(checks.gt(BigInt(0), params)); + }, + negative(params) { + return this.check(checks.lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(checks.lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(checks.gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(checks.multipleOf(value, params)); + }, +}))); +function schemas_bigint(params) { + return core._bigint(ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}))); +function int64(params) { + return core._int64(ZodBigIntFormat, params); +} +function uint64(params) { + return core._uint64(ZodBigIntFormat, params); +} +const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); +}))); +function symbol(params) { + return core._symbol(ZodSymbol, params); +} +const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); +}))); +function schemas_undefined(params) { + return core._undefined(ZodUndefined, params); +} + +const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function schemas_null(params) { + return api_null(ZodNull, params); +} + +const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); +}); +function any() { + return _any(ZodAny); +} +const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return _never(ZodNever, params); +} +const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); +}))); +function schemas_void(params) { + return core._void(ZodVoid, params); +} + +const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}))); +function schemas_date(params) { + return core._date(ZodDate, params); +} +const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + }, +}); +function schemas_array(element, params) { + return _array(ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); +} +const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return schemas_enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall: catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: undefined }); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_required(ZodNonOptional, this, args[0]); + }, +}); +function schemas_object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params), + }; + return new ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util.normalizeParams(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params), + }); +} +const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function schemas_union(options, params) { + return new ZodUnion({ + type: "union", + options: options, + ...normalizeParams(params), + }); +} +const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}))); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options: options, + discriminator, + ...normalizeParams(params), + }); +} +const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest: rest, + }); + }, + partial() { + const def = this._zod.def; + // a refinement was authored against the full arity; partialing would run it on a shorter array + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), + }); + }, +}))); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...util.normalizeParams(params), + }); +} +const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function schemas_record(keyType, valueType, params) { + // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: schemas_string(), + valueType: keyType, + ...normalizeParams(valueType), + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...util.normalizeParams(params), + partial: true, + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...util.normalizeParams(params), + }); +} +const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; +}); +function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}))); +function schemas_file(params) { + return core._file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function schemas_optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function schemas_nullish(innerType) { + return schemas_optional(nullable(innerType)); +} +const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function schemas_default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params), + }); +} +const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function schemas_catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), + }); +} + +const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); +}))); +function nan(params) { + return core._nan(ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodCodec.init(inst, def); +}))); +function schemas_codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +function invertCodec(codec) { + const def = codec._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform, + }); +} +const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { + core.$ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); +}))); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { + core.$ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function schemas_promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { + core.$ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); +}))); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +// custom checks +function schemas_check(fn) { + const ch = new core.$ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return core._custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn, params) { + return _superRefine(fn, params); +} +// Re-export describe and meta from core +const schemas_describe = describe; +const schemas_meta = api_meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util.normalizeParams(params), + }); + inst._zod.bag.Class = cls; + // Override check to emit invalid_type instead of custom + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(inst._zod.def.path ?? [])], + }); + } + }; + return inst; +} + +// stringbool +const stringbool = (...args) => core._stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString, +}, ...args); +function schemas_json(params) { + const jsonSchema = lazy(() => { + return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema, + }); +} + + + + +function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); +} +function iso_date(params) { + return _isoDate(ZodISODate, params); +} +function iso_time(params) { + return core._isoTime(ZodISOTime, params); +} +function iso_duration(params) { + return core._isoDuration(ZodISODuration, params); +} + +// Zod 3 compat layer + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +const ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom", +}; + +/** @deprecated Use `z.config(params)` instead. */ +function setErrorMap(map) { + core.config({ + customError: map, + }); +} +/** @deprecated Use `z.config()` instead. */ +function getErrorMap() { + return core.config().customError; +} +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var compat_ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { +})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); + + + +function coerce_string(params) { + return core._coercedString(schemas.ZodString, params); +} +function coerce_number(params) { + return _coercedNumber(ZodNumber, params); +} +function coerce_boolean(params) { + return core._coercedBoolean(schemas.ZodBoolean, params); +} +function coerce_bigint(params) { + return core._coercedBigint(schemas.ZodBigInt, params); +} +function coerce_date(params) { + return core._coercedDate(schemas.ZodDate, params); +} + + + +//#region src/constants.ts +const LATEST_PROTOCOL_VERSION = "2025-11-25"; +const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +/** +* `_meta` key associating a message with a 2025-11-25 task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +/** +* `_meta` key carrying the MCP protocol version governing a request. +* +* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. +*/ +const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; +/** +* `_meta` key identifying the client software making a request. +* +* Clients SHOULD include it on every request; the value is self-reported and +* intended for display, logging, and debugging — servers should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; +/** +* `_meta` key identifying the server software producing a response. +* +* Servers SHOULD include it on every response; the value is self-reported and +* intended for display, logging, and debugging — clients should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; +/** +* `_meta` key carrying the client's capabilities for a request. +* +* Capabilities are declared per request rather than once at initialization; +* servers must not infer capabilities from prior requests. +*/ +const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; +/** +* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request +* that opened the stream a notification was delivered on. +* +* Stamped by the server on every notification delivered via a +* `subscriptions/listen` stream (including the leading +* `notifications/subscriptions/acknowledged`); on stdio, where all messages +* share one channel, clients use it to correlate notifications with their +* originating subscription. The value is the listen request's JSON-RPC ID +* verbatim. +*/ +const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; +/** +* `_meta` key carrying the desired log level for a request. +* +* When absent, the server must not send `notifications/message` notifications +* for the request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. +*/ +const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; +/** +* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `traceparent` header format, +* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. +* +* @see https://www.w3.org/TR/trace-context/#traceparent-header +*/ +const TRACEPARENT_META_KEY = "traceparent"; +/** +* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `tracestate` header format, +* e.g. `vendor1=value1,vendor2=value2`. +* +* @see https://www.w3.org/TR/trace-context/#tracestate-header +*/ +const TRACESTATE_META_KEY = "tracestate"; +/** +* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C Baggage header format, +* e.g. `userId=alice,serverRegion=us-east-1`. +* +* @see https://www.w3.org/TR/baggage/ +*/ +const BAGGAGE_META_KEY = "baggage"; +const JSONRPC_VERSION = "2.0"; +const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); +const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); +const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); +const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); +const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); + +//#endregion +//#region src/schemas.ts +const JSONValueSchema = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema), + schemas_array(JSONValueSchema) +])); +const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); +const JSONArraySchema = schemas_array(JSONValueSchema); +/** +* A progress token, used to associate progress notifications with the original request. +*/ +const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* An opaque token used to represent a cursor for pagination. +*/ +const CursorSchema = schemas_string(); +/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ +const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); +/** +* Metadata for associating messages with a task. +* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); +const RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** +* Common params for any request. +*/ +const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +/** +* Common params for any task-augmented request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); +const RequestSchema = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +const NotificationSchema = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema.loose().optional() +}); +/** +* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). +* Loose — implementation-specific keys pass through. +* +* The serverInfo key identifies the server software producing the response +* (servers SHOULD include it on every response; the value is self-reported +* and intended for display, logging, and debugging). The getter defers the +* `ImplementationSchema` reference, which is declared later in this file. +*/ +const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); +} }); +const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); +/** +* A uniquely identifying ID for a request in JSON-RPC. +*/ +const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* A request that expects a response. +*/ +const JSONRPCRequestSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +/** +* A notification which does not expect a response. +*/ +const JSONRPCNotificationSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +/** +* A successful (non-error) response to a request. +*/ +const JSONRPCResultResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +/** +* A response to a request that indicates an error occurred. +*/ +const JSONRPCErrorResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: schemas_object({ + code: schemas_number().int(), + message: schemas_string(), + data: unknown().optional() + }) +}).strict(); +const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/** +* A response that indicates success but carries no data. +*/ +const EmptyResultSchema = ResultSchema.strict(); +const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: schemas_string().optional() +}); +/** +* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. +* +* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. +* +* This notification indicates that the result will be unused, so any associated processing SHOULD cease. +* +* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. +*/ +const CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +/** +* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. +*/ +const IconSchema = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() +}); +/** +* Base schema to add `icons` property. +* +*/ +const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); +/** +* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. +*/ +const BaseMetadataSchema = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() +}); +/** +* Describes the name and version of an MCP implementation. +*/ +const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() +}); +const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); +const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; +}, intersection(schemas_object({ + form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() +}), JSONObjectSchema.optional())); +/** +* Task capabilities for clients, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() +}); +/** +* Task capabilities for servers, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() +}); +/** +* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. +*/ +const ClientCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + sampling: schemas_object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** +* This request is sent from the client to the server when it first connects, asking it to begin initialization. +*/ +const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +/** +* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. +*/ +const ServerCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +/** +* After receiving an initialize request from the client, the server sends this response. +*/ +const InitializeResultSchema = ResultSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: schemas_string().optional() +}); +/** +* This notification is sent from the client to the server after initialization has finished. +*/ +const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +/** +* A request from the client asking the server to advertise its supported protocol +* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers +* MUST implement `server/discover`. Clients MAY call it but are not required to — +* version negotiation can also happen inline via the per-request `_meta` envelope. +*/ +const DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The result returned by the server for a `server/discover` request. +*/ +const DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilitiesSchema, + instructions: schemas_string().optional() +}); +/** +* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. +*/ +const PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +const ProgressSchema = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) +}); +const ProgressNotificationParamsSchema = schemas_object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema +}); +/** +* An out-of-band notification used to inform the receiver of a progress update for a long-running request. +* +* @category notifications/progress +*/ +const ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); +const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); +/** +* The contents of a specific resource or sub-resource. +*/ +const ResourceContentsSchema = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); +/** +* A Zod schema for validating Base64 strings that is more performant and +* robust for very large inputs than the default regex-based check. It avoids +* stack overflows by using the native `atob` function for validation. +*/ +const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); +/** +* The sender or recipient of messages and data in a conversation. +*/ +const RoleSchema = schemas_enum(["user", "assistant"]); +/** +* Optional annotations providing clients additional context about a resource. +*/ +const AnnotationsSchema = schemas_object({ + audience: schemas_array(RoleSchema).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() +}); +/** +* A known resource that the server is capable of reading. +*/ +const ResourceSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* A template description for resources available on the server. +*/ +const ResourceTemplateSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of resources the server has. +*/ +const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +/** +* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. +*/ +const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); +/** +* Sent from the client to request a list of resource templates the server has. +*/ +const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +/** +* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. +*/ +const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); +const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); +/** +* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. +*/ +const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to the server, to read a specific resource URI. +*/ +const ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +/** +* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. +*/ +const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +/** +* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. +*/ +const SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +/** +* The set of notification types a client opts in to on a `subscriptions/listen` +* request. Each type is opt-in; the server MUST NOT send a notification type +* the client has not explicitly requested here. +*/ +const SubscriptionFilterSchema = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() +}); +const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent from the client to open a long-lived channel for receiving notifications +* outside the context of a specific request (protocol revision 2026-07-28). +* Replaces the previous HTTP GET endpoint and `resources/subscribe`. +*/ +const SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema +}); +const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent by the server as the first message on a `subscriptions/listen` stream +* to acknowledge that the subscription has been established and report which +* notification types it agreed to honor (protocol revision 2026-07-28). +*/ +const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); +/** +* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's +* JSON-RPC ID under the canonical subscription-id key (mirroring the same key +* on every notification delivered on the stream). Extends +* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed +* here too. +*/ +const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); +/** +* The response to a `subscriptions/listen` request, signalling that the +* subscription has ended gracefully (for example, during server shutdown). +* Because the listen stream is long-lived, this result is sent only when the +* server tears the subscription down; an abrupt transport close carries no +* response. The result body is otherwise empty. +*/ +const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); +/** +* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. +*/ +const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); +/** +* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +/** +* Describes an argument that a prompt can accept. +*/ +const PromptArgumentSchema = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) +}); +/** +* A prompt or prompt template that the server offers. +*/ +const PromptSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema)), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of prompts and prompt templates the server has. +*/ +const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +/** +* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. +*/ +const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); +/** +* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. +*/ +const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() +}); +/** +* Used by the client to get a prompt provided by the server. +*/ +const GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +/** +* Text provided to or from an LLM. +*/ +const TextContentSchema = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* An image provided to or from an LLM. +*/ +const ImageContentSchema = schemas_object({ + type: literal("image"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Audio content provided to or from an LLM. +*/ +const AudioContentSchema = schemas_object({ + type: literal("audio"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A tool call request from an assistant (LLM). +* Represents the assistant's request to use a tool. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolUseContentSchema = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* The contents of a resource, embedded into a prompt or tool call result. +*/ +const EmbeddedResourceSchema = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A resource that the server is capable of reading, included in a prompt or tool call result. +* +* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. +*/ +const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); +/** +* A content block that can be used in prompts and tool results. +*/ +const ContentBlockSchema = schemas_union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** +* Describes a message returned as part of a prompt. +*/ +const PromptMessageSchema = schemas_object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** +* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. +*/ +const GetPromptResultSchema = ResultSchema.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema) +}); +/** +* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Additional properties describing a `Tool` to clients. +* +* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. +* They are not guaranteed to provide a faithful description of +* tool behavior (including descriptive properties like `title`). +* +* Clients should never make tool use decisions based on `ToolAnnotations` +* received from untrusted servers. +*/ +const ToolAnnotationsSchema = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() +}); +/** +* Execution-related properties for a tool. +*/ +const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" +]).optional() }); +/** +* Definition for a tool the client can call. +*/ +const ToolSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the client to request a list of tools the server has. +*/ +const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +/** +* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. +*/ +const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); +/** +* The server's response to a tool call. +*/ +const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ + content: schemas_array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() +}); +/** +* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. +*/ +const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +/** +* Parameters for a `tools/call` request. +*/ +const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Used by the client to invoke a tool provided by the server. +*/ +const CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +/** +* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Base schema for list changed subscription options (without callback). +* Used internally for Zod validation of `autoRefresh` and `debounceMs`. +*/ +const ListChangedOptionsBaseSchema = schemas_object({ + autoRefresh: schemas_boolean().default(true), + debounceMs: schemas_number().int().nonnegative().default(300) +}); +/** +* The severity of a log message. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingLevelSchema = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* Parameters for a `logging/setLevel` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); +/** +* A request from the client to the server, to enable or adjust logging. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +/** +* Parameters for a `notifications/message` notification. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: schemas_string().optional(), + data: unknown() +}); +/** +* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +/** +* Hints to use for model selection. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); +/** +* The server's preferences for model selection, requested of the client during sampling. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelPreferencesSchema = schemas_object({ + hints: schemas_array(ModelHintSchema).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() +}); +/** +* Controls tool usage behavior in sampling requests. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" +]).optional() }); +/** +* The result of a tool execution, provided by the user (server). +* Represents the outcome of invoking a tool requested via `ToolUseContent`. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolResultContentSchema = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Basic content types for sampling responses (without tool use). +* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +/** +* Content block types allowed in sampling messages. +* This includes text, image, audio, tool use requests, and tool results. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** +* Describes a message issued to or received from an LLM API. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageSchema = schemas_object({ + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Parameters for a `sampling/createMessage` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + messages: schemas_array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema.optional(), + tools: schemas_array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() +}); +/** +* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +/** +* The client's response to a `sampling/create_message` request from the server. +* This is the backwards-compatible version that returns single content (no arrays). +* Used when the request does not include tools. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema, + content: SamplingContentSchema +}); +/** +* The client's response to a `sampling/create_message` request when tools were provided. +* This version supports array content for tool use flows. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) +}); +/** +* Primitive schema definition for boolean fields. +*/ +const BooleanSchemaSchema = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() +}); +/** +* Primitive schema definition for string fields. +*/ +const StringSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() +}); +/** +* Primitive schema definition for number fields. +*/ +const NumberSchemaSchema = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() +}); +/** +* Schema for single-selection enumeration without display titles for options. +*/ +const UntitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() +}); +/** +* Schema for single-selection enumeration with display titles for each option. +*/ +const TitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() +}); +/** +* Use {@linkcode TitledSingleSelectEnumSchema} instead. +* This interface will be removed in a future version. +*/ +const LegacyTitledEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() +}); +const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** +* Schema for multiple-selection enumeration without display titles for options. +*/ +const UntitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Schema for multiple-selection enumeration with display titles for each option. +*/ +const TitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Combined schema for multiple-selection enumeration +*/ +const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** +* Primitive schema definition for enum fields. +*/ +const EnumSchemaSchema = schemas_union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema +]); +/** +* Union of all primitive schema definitions. +*/ +const PrimitiveSchemaDefinitionSchema = schemas_union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +/** +* Parameters for an `elicitation/create` request for form-based elicitation. +*/ +const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) +}); +/** +* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. +*/ +const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() +}); +/** +* The parameters for a request to elicit additional information from the user via the client. +*/ +const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** +* A request from the server to elicit user input via the client. +* The client should present the message and form fields to the user (form mode) +* or navigate to a URL (URL mode). +*/ +const ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +/** +* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); +/** +* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +/** +* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. +*/ +const ElicitResultSchema = ResultSchema.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) +}); +/** +* A reference to a resource or resource template definition. +*/ +const ResourceTemplateReferenceSchema = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() +}); +/** +* Identifies a prompt. +*/ +const PromptReferenceSchema = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() +}); +/** +* Parameters for a {@linkcode CompleteRequest | completion/complete} request. +*/ +const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() +}); +/** +* A request from the client to the server, to ask for completion options. +*/ +const CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +/** +* The server's response to a {@linkcode CompleteRequest | completion/complete} request +*/ +const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) +}) }); +/** +* Represents a root directory or file that the server can operate on. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootSchema = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the server to request a list of root URIs from the client. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The client's response to a `roots/list` request from the server. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); +/** +* A notification from the client to the server, informing it that the list of roots has changed. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Task creation parameters, used to ask that the server create a task to represent a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskCreationParamsSchema = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() +}); +/** +* The status of a task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusSchema = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +/** +* A pollable state object associated with a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskSchema = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) +}); +/** +* Result returned when a task is created, containing the task data wrapped in a `task` field. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +/** +* Parameters for task status notification. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** +* A notification sent when a task's status changes. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +/** +* A request to get the state of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode GetTaskRequest | tasks/get} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* A request to get the result of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a `tasks/result` request. +* The structure matches the result type of the original request. +* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. +* +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** +* A request to list tasks. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +/** +* The response to a {@linkcode ListTasksRequest | tasks/list} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); +/** +* A request to cancel a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +const ClientRequestSchema = schemas_union([ + PingRequestSchema, + auth_CUe6YdwF_InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +const ClientNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + auth_CUe6YdwF_InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +const ClientResultSchema = schemas_union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); +const ServerRequestSchema = schemas_union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema +]); +const ServerNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +const ServerResultSchema = schemas_union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + auth_CUe6YdwF_CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); + +//#endregion +//#region src/auth.ts +/** +* Reusable URL validation that disallows `javascript:` scheme +*/ +const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url) => { + const u = new URL(url); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +/** +* RFC 9728 OAuth Protected Resource Metadata +*/ +const OAuthProtectedResourceMetadataSchema = looseObject({ + resource: schemas_string().url(), + authorization_servers: schemas_array(SafeUrlSchema).optional(), + jwks_uri: schemas_string().url().optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + bearer_methods_supported: schemas_array(schemas_string()).optional(), + resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + resource_name: schemas_string().optional(), + resource_documentation: schemas_string().optional(), + resource_policy_uri: schemas_string().url().optional(), + resource_tos_uri: schemas_string().url().optional(), + tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), + authorization_details_types_supported: schemas_array(schemas_string()).optional(), + dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + dpop_bound_access_tokens_required: schemas_boolean().optional() +}); +/** +* RFC 8414 OAuth 2.0 Authorization Server Metadata +*/ +const OAuthMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint: schemas_string().optional(), + introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + code_challenge_methods_supported: schemas_array(schemas_string()).optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery 1.0 Provider Metadata +* +* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata +*/ +const OpenIdProviderMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + acr_values_supported: schemas_array(schemas_string()).optional(), + subject_types_supported: schemas_array(schemas_string()), + id_token_signing_alg_values_supported: schemas_array(schemas_string()), + id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + display_values_supported: schemas_array(schemas_string()).optional(), + claim_types_supported: schemas_array(schemas_string()).optional(), + claims_supported: schemas_array(schemas_string()).optional(), + service_documentation: schemas_string().optional(), + claims_locales_supported: schemas_array(schemas_string()).optional(), + ui_locales_supported: schemas_array(schemas_string()).optional(), + claims_parameter_supported: schemas_boolean().optional(), + request_parameter_supported: schemas_boolean().optional(), + request_uri_parameter_supported: schemas_boolean().optional(), + require_request_uri_registration: schemas_boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery metadata that may include OAuth 2.0 fields +* This schema represents the real-world scenario where OIDC providers +* return a mix of OpenID Connect and OAuth 2.0 metadata fields +*/ +const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +/** +* OAuth 2.1 token response +*/ +const OAuthTokensSchema = schemas_object({ + access_token: schemas_string(), + id_token: schemas_string().optional(), + token_type: schemas_string(), + expires_in: coerce_number().optional(), + scope: schemas_string().optional(), + refresh_token: schemas_string().optional() +}).strip(); +/** +* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. +* +* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when +* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, +* so strict checking rejects conformant IdPs. +*/ +const IdJagTokenExchangeResponseSchema = schemas_object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: schemas_string(), + token_type: schemas_string().optional(), + expires_in: schemas_number().optional(), + scope: schemas_string().optional() +}).strip(); +/** +* OAuth 2.1 error response +*/ +const OAuthErrorResponseSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional(), + error_uri: schemas_string().optional() +}); +/** +* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` +*/ +const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata +*/ +const OAuthClientMetadataSchema = schemas_object({ + redirect_uris: schemas_array(SafeUrlSchema), + token_endpoint_auth_method: schemas_string().optional(), + grant_types: schemas_array(schemas_string()).optional(), + response_types: schemas_array(schemas_string()).optional(), + application_type: schemas_string().optional(), + client_name: schemas_string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: schemas_string().optional(), + contacts: schemas_array(schemas_string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: schemas_string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: schemas_string().optional(), + software_version: schemas_string().optional(), + software_statement: schemas_string().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration client information +*/ +const OAuthClientInformationSchema = schemas_object({ + client_id: schemas_string(), + client_secret: schemas_string().optional(), + client_id_issued_at: schemas_number().optional(), + client_secret_expires_at: schemas_number().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) +*/ +const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration error response +*/ +const OAuthClientRegistrationErrorSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional() +}).strip(); +/** +* RFC 7009 OAuth 2.0 Token Revocation request +*/ +const OAuthTokenRevocationRequestSchema = schemas_object({ + token: schemas_string(), + token_type_hint: schemas_string().optional() +}).strip(); + +//#endregion + +//# sourceMappingURL=auth-CUe6YdwF.mjs.map + + + + + + + + +//#region ../core-internal/src/errors/crossBundleBrand.ts +/** +* Cross-bundle `instanceof` support for the SDK error classes. +* +* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their +* own copy of `core-internal`, so an error constructed by one package fails a +* prototype-identity `instanceof` against the same class re-exported by the other — +* exactly the check a dual-role process (gateway, host, in-process test) writes. +* +* Instead of prototype identity, branded classes stamp every instance with the brand +* strings of its class chain under a registry symbol (`Symbol.for`, shared across +* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the +* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior +* is unchanged for anything unbranded. +* +* A class participates by defining an **own** `mcpBrand` static (via a `static {}` +* block, so nothing reaches the declaration files — a declared `protected static` +* field would make the constructor types nominally incompatible across the bundled +* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as +* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand +* keep plain prototype semantics — a foreign base-class instance never satisfies +* `instanceof UserSubclass`. +* +* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core +* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), +* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios +* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a +* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 +* (Symbol.hasInstance on every schema class for cross-version interop). +* +* Contract notes: +* - Participation criterion: **every error class exported from a public package that +* callers are documented to `instanceof` must be branded.** The per-package +* errorBrandConformance tests walk the export surfaces and fail naming any +* exported Error subclass that has not opted in. +* - Brands assert **identity, not shape**: brand strings are version-less, so an +* instance from one SDK version matches the class of another. Members added to a +* branded class in a later version may be absent on a matched instance — read +* fields defensively, and treat branded classes as additive-only. The escape +* hatch when a release must break a branded class's read contract: change that +* class's brand string in the same release, which cleanly severs cross-version +* matching for that class. The per-package brand pins make the rename +* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each +* package's errorBrandConformance test pins its package-local ones. +* - Cross-bundle matching requires **both** copies to be at or after the release +* that introduced branding; against an older copy, behavior degrades to plain +* prototype `instanceof` in both directions. +* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would +* break the brand statics; default esbuild/webpack/terser settings do not. +*/ +/** Registry symbol — identical across bundled copies and realms. */ +const BRANDS = Symbol.for("mcp.sdk.errorBrands"); +/** +* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an +* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — +* subclasses inherit the stamping without touching their constructors. +* +* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would +* satisfy `instanceof` while lacking the prototype members (getters like `.status`) +* that callers reach for after the check. +*/ +function stampErrorBrands(instance, ctor) { + const brands = /* @__PURE__ */ new Set(); + let current = ctor; + while (typeof current === "function") { + const brand = current.mcpBrand; + if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); + current = Object.getPrototypeOf(current); + } + if (brands.size === 0) return; + Object.defineProperty(instance, BRANDS, { + value: brands, + enumerable: false, + configurable: true + }); +} +/** +* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the +* value carries the **own** brand of the class being tested against (cross-bundle +* path), falling back to ordinary prototype-based `instanceof` otherwise. +*/ +function brandedHasInstance(cls, value) { + try { + if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { + const carried = value[BRANDS]; + if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; + } + } catch {} + return Function.prototype[Symbol.hasInstance].call(cls, value); +} + +//#endregion +//#region ../core-internal/src/auth/errors.ts +/** +* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} +* and extensions. +*/ +let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { + /** + * The request is missing a required parameter, includes an invalid parameter value, + * includes a parameter more than once, or is otherwise malformed. + */ + OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; + /** + * Client authentication failed (e.g., unknown client, no client authentication included, + * or unsupported authentication method). + */ + OAuthErrorCode$1["InvalidClient"] = "invalid_client"; + /** + * The provided authorization grant or refresh token is invalid, expired, revoked, + * does not match the redirection URI used in the authorization request, or was issued to another client. + */ + OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; + /** + * The authenticated client is not authorized to use this authorization grant type. + */ + OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; + /** + * The authorization grant type is not supported by the authorization server. + */ + OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; + /** + * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. + */ + OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; + /** + * The resource owner or authorization server denied the request. + */ + OAuthErrorCode$1["AccessDenied"] = "access_denied"; + /** + * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. + */ + OAuthErrorCode$1["ServerError"] = "server_error"; + /** + * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. + */ + OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; + /** + * The authorization server does not support obtaining an authorization code using this method. + */ + OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; + /** + * The authorization server does not support the requested token type. + */ + OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; + /** + * The access token provided is expired, revoked, malformed, or invalid for other reasons. + */ + OAuthErrorCode$1["InvalidToken"] = "invalid_token"; + /** + * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) + */ + OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; + /** + * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) + */ + OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; + /** + * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) + */ + OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; + /** + * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) + */ + OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; + /** + * The request requires higher privileges than provided by the access token. + */ + OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; + /** + * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) + */ + OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; + return OAuthErrorCode$1; +}({}))); +/** +* OAuth error class for all OAuth-related errors. +*/ +var src_CX2iR2pK_OAuthError = class OAuthError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, errorUri) { + super(message); + this.code = code; + this.errorUri = errorUri; + this.name = "OAuthError"; + stampErrorBrands(this, new.target); + } + /** + * Converts the error to a standard OAuth error response object. + */ + toResponseObject() { + const response = { + error: this.code, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + /** + * Creates an {@linkcode OAuthError} from an OAuth error response. + */ + static fromResponse(response) { + return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); + } +}; + +//#endregion +//#region ../core-internal/src/errors/sdkErrors.ts +/** +* Error codes for SDK errors (local errors that never cross the wire). +* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses +* descriptive string values for better developer experience. +* +* These errors are thrown locally by the SDK and are never serialized as +* JSON-RPC error responses. +*/ +let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { + /** Transport is not connected */ + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + /** Transport is already connected */ + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + /** Protocol is not initialized */ + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + /** Required capability is not supported by the remote side */ + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + /** Request timed out waiting for response */ + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + /** Connection was closed */ + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + /** Failed to send message */ + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + /** Response result failed local schema validation */ + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + /** + * The response carried a `resultType` discriminator (protocol revision + * 2026-07-28) naming a result kind this client cannot consume yet, e.g. + * `input_required`. The kind is carried in `data.resultType`. + */ + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + /** + * The multi-round-trip auto-fulfilment driver exhausted its round cap + * (`inputRequired.maxRounds`) without the server returning a complete + * result. `data.rounds` carries the cap that was hit and + * `data.lastResult` carries the last `input_required` payload received + * (`{ inputRequests, requestState? }`), so callers can inspect or resume + * the flow manually. + */ + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + /** + * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / + * `listResources()` / `listResourceTemplates()` walk hit the + * `ClientOptions.listMaxPages` cap without the server's pagination + * converging. `data.method` carries the list verb and + * `data.listMaxPages` the cap that was hit; raise the cap or fall back to + * explicit per-page `{ cursor }` calls. + */ + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + /** + * The spec method being sent does not exist on the negotiated protocol + * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or + * `server/discover` toward a 2025-era peer). Raised locally, before + * anything reaches the transport. The method and era are carried in + * `data.method` / `data.era`. + */ + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + /** + * Protocol-era negotiation at connect time failed without producing either a + * usable modern (2026-07-28+) era or a definitive legacy fallback signal — + * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a + * network failure, or the server answered the probe with a 5xx (a typed + * connect error, never an era verdict). + * + * Negotiation-phase only: this code is never used once an era is + * established. Auth walls never carry it: a 401/403 rejecting the probe + * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} + * instead, so era-recovery flows keyed on this code (e.g. cached-verdict + * gateways) can never persist a verdict for an unauthorized exchange. + */ + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + /** + * HTTP 401 authentication failure: the transport's re-auth retry still got + * 401 (`Server returned 401 after re-authentication`), or the version + * negotiation probe was rejected 401 with no `authProvider` configured + * (`Version negotiation failed: the server requires authorization (HTTP 401)`). + * Carried on an {@linkcode SdkHttpError} with `status: 401`. + */ + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + /** + * HTTP 403 denial: the step-up re-authorization retry limit was reached, + * or the version negotiation probe was rejected 403 + * (`Version negotiation failed: the server denied access (HTTP 403)`). + * Carried on an {@linkcode SdkHttpError} with `status: 403`. + */ + SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; + SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; + SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; + SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; + return SdkErrorCode$1; +}({}); +/** +* SDK errors are local errors that never cross the wire. +* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors +* that are serialized and sent as error responses. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" +* try { +* // Throwing an SDK error +* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); +* } catch (error) { +* // Checking error type by code +* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { +* // Handle timeout +* } +* } +* ``` +*/ +var src_CX2iR2pK_SdkError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } +}; +/** +* An {@linkcode SdkError} subclass for HTTP transport failures. +* +* Thrown by the streamable HTTP transport when the server responds with a +* non-OK status code. Narrows {@linkcode SdkError.data | data} to +* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status +* without unsafe casting. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" +* if (error instanceof SdkHttpError) { +* console.log(error.status); // number +* console.log(error.statusText); // string | undefined +* } +* ``` +*/ +var SdkHttpError = class extends src_CX2iR2pK_SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message, data) { + super(code, message, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } +}; + +//#endregion +//#region ../core-internal/src/shared/authUtils.ts +/** +* Utilities for handling OAuth resource URIs. +*/ +/** +* Converts a server URL to a resource URL by removing the fragment. +* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} +* states that resource URIs "MUST NOT include a fragment component". +* Keeps everything else unchanged (scheme, domain, port, path, query). +*/ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); + resourceURL.hash = ""; + return resourceURL; +} +/** +* Checks if a requested resource URL matches a configured resource URL. +* A requested resource matches if it has the same scheme, domain, port, +* and its path starts with the configured resource's path. +* +* @param options - The options object +* @param options.requestedResource - The resource URL being requested +* @param options.configuredResource - The resource URL that has been configured +* @returns true if the requested resource matches the configured resource, false otherwise +*/ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) return false; + if (requested.pathname.length < configured.pathname.length) return false; + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} + +//#endregion +//#region ../core-internal/src/shared/clientCapabilityRequirements.ts +/** +* Inbound request methods whose processing structurally requires a client +* capability, keyed by method, valued by the capabilities required. +* +* Currently empty: none of the request methods served on the 2026-07-28 +* registry unconditionally requires a client capability. Entries appear here +* when such methods exist — for example requests whose handling embeds +* elicitation or sampling input requests (the input-request engine), or +* opt-in subscription delivery. Handler-conditional requirements (a specific +* tool that needs sampling) are not expressible as a static method table and +* are enforced at the point the requirement arises instead. +*/ +const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); +/** +* The client capabilities a request method structurally requires, or +* `undefined` when the method has no static requirement. +*/ +function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { + return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; +} +function isPlainObject$7(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Whether a required nested member counts as declared even though it is not +* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at +* all) is read as form support — the pre-mode (2025) meaning of a bare +* declaration — so an `elicitation.form` requirement treats it as satisfied. +* Declaring any mode explicitly (for example `elicitation: { url: {} }`) +* removes the implication. +*/ +function isImpliedCapabilityMember(capability, member, declaredValue) { + return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; +} +/** +* The client capabilities an embedded multi-round-trip input request requires +* (call site 2 — the outbound input-request leg): a server MUST NOT send an +* `inputRequests` kind the request's declared client capabilities do not +* cover. Returns `undefined` for entries whose method is not one of the +* embedded input-request kinds (those are a server bug handled separately, +* not a capability question). +* +* The requirement is mode-aware where the capability is: URL-mode elicitation +* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires +* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a +* mode the client did not declare); sampling with `tools`/`toolChoice` +* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies +* the form requirement — see {@linkcode missingClientCapabilities}. +*/ +function requiredClientCapabilitiesForInputRequest(entry) { + switch (entry.method) { + case "elicitation/create": + if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; + return { elicitation: { form: {} } }; + case "sampling/createMessage": { + const params = entry.params; + if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; + return { sampling: {} }; + } + case "roots/list": return { roots: {} }; + default: return; + } +} +/** +* Computes the subset of `required` client capabilities the client did not +* declare. Returns `undefined` when every required capability is declared; +* otherwise returns an object in the `ClientCapabilities` shape containing +* exactly the missing capabilities (suitable for +* `data.requiredCapabilities` on the `-32021` error). +* +* A capability counts as declared when its top-level key is present on the +* declared capabilities; when the requirement names nested members (for +* example `elicitation: { url: {} }`), each named member must also be present +* under the declared capability. One lenient reading applies: a bare +* `elicitation: {}` declaration (no mode sub-capability at all) counts as +* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare +* declaration. An absent or empty `declared` value means +* nothing is declared — every required capability is missing (the structural +* clean-refusal posture for sessions with no per-request capability view). +*/ +function src_CX2iR2pK_missingClientCapabilities(required, declared) { + const missing = {}; + for (const [capability, requirement] of Object.entries(required)) { + if (requirement === void 0) continue; + const declaredValue = declared === void 0 ? void 0 : declared[capability]; + if (declaredValue === void 0) { + missing[capability] = requirement; + continue; + } + if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { + const missingMembers = {}; + for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; + if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; + } + } + return Object.keys(missing).length > 0 ? missing : void 0; +} + +//#endregion +//#region ../core-internal/src/shared/protocolEras.ts +/** +* The first protocol revision of the modern (2026-07-28) era. Revision identifiers +* are ISO dates, so lexicographic comparison orders them chronologically. +*/ +const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; +/** +* Modern-era protocol revisions this SDK can negotiate via `server/discover`. +* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy +* `initialize` list), so adding a revision here can never leak a modern version +* string into a 2025-era handshake. Internal — not part of the public API surface. +*/ +const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); +/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ +function isModernProtocolVersion(version) { + return version >= FIRST_MODERN_PROTOCOL_VERSION; +} +/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ +function legacyProtocolVersions(versions) { + return versions.filter((version) => !isModernProtocolVersion(version)); +} +/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ +function modernProtocolVersions(versions) { + return versions.filter((version) => isModernProtocolVersion(version)); +} + +//#endregion +//#region ../core-internal/src/wire/textFallback.ts +/** +* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH +* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` +* is a non-object value (array/primitive/`null`) and the handler authored no +* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. +* Object-shaped (or absent) `structuredContent` returns the same reference. +* +* Leaf module: imported by both era codec modules, so it must NOT import from +* `./codec.js` (which value-imports the rev codecs at top level — that would +* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec +* module first). +*/ +function appendTextFallbackForNonObject(result) { + const sc = result.structuredContent; + if (sc === void 0) return result; + if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; + if (result.content?.some((c) => c.type === "text") ?? false) return result; + return { + ...result, + content: [...result.content ?? [], { + type: "text", + text: JSON.stringify(sc) + }] + }; +} + +//#endregion +//#region ../core-internal/src/wire/resultFamilies.ts +/** +* Result-family keys that must never default into a `{content: []}` tools/call +* success. Shared by the 2025 wire-seam schema and server normalization. +* Leaf module (like `textFallback.ts`): imported by registry/server paths, so +* it must NOT import from `./codec.js` — that would close a runtime cycle. +*/ +const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" +]; +/** +* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and +* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. +*/ +function normalizeContentlessToolResult(value) { + if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; + return { + ...value, + content: [] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts +/** +* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from +* the public/neutral types/schemas.ts. The neutral layer is the public-API +* superset and is free to evolve (e.g., SEP-2106 widening); this file is the +* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. +* +* This is the era's complete frozen wire-parse contract — both the 2025-only +* delta (the deprecated task family, the era role unions) AND frozen copies of +* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, +* prompts/resources/completion/elicitation, …). The 2026-era codec +* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. +* +* The 2025-only delta (the task message surface, restored types-only by #2248 +* for interop with task-capable 2025 peers) is parsed ONLY through this era's +* registry; the deprecated Task* schemas also live (marked `@deprecated`) in +* the neutral schema layer so the public types stay nameable without a +* cross-layer import — nameability is constant, runtime availability is +* version-keyed — but appear in no API signature. Q1 increment 2 — deletions +* are physical: the +* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do +* carry the deprecated Task* sub-schemas by composition — soft contamination, +* tracked for anchor-exactness adjudication). +* +* The only cross-layer dependency is `import type { JSONObject, JSONValue }` +* from the neutral types barrel — pure structural type aliases with no parse +* behavior. No runtime schema is shared with the neutral layer. +*/ +function build$1() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + /** + * Common params for any request. + */ + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** + * Common params for any task-augmented request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * A response that indicates success but carries no data. + */ + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: schemas_string().optional() + }); + /** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. + */ + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + /** + * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. + */ + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + /** + * Base schema to add `icons` property. + * + */ + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + /** + * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. + */ + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + /** + * Describes the name and version of an MCP implementation. + */ + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** + * Task capabilities for clients, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** + * Task capabilities for servers, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + /** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + /** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + /** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + /** + * After receiving an initialize request from the client, the server sends this response. + */ + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: schemas_string().optional() + }); + /** + * This notification is sent from the client to the server after initialization has finished. + */ + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + /** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); + const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); + const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); + /** + * The contents of a specific resource or sub-resource. + */ + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * Optional annotations providing clients additional context about a resource. + */ + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + /** + * A known resource that the server is capable of reading. + */ + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * A template description for resources available on the server. + */ + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of resources the server has. + */ + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + /** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); + /** + * Sent from the client to request a list of resource templates the server has. + */ + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + /** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); + /** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to the server, to read a specific resource URI. + */ + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + /** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + /** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + /** + * Describes an argument that a prompt can accept. + */ + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + /** + * A prompt or prompt template that the server offers. + */ + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + /** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); + /** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }); + /** + * Used by the client to get a prompt provided by the server. + */ + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + /** + * Text provided to or from an LLM. + */ + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * An image provided to or from an LLM. + */ + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Audio content provided to or from an LLM. + */ + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * The contents of a resource, embedded into a prompt or tool call result. + */ + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. + */ + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + /** + * A content block that can be used in prompts and tool results. + */ + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + /** + * Describes a message returned as part of a prompt. + */ + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + /** + * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. + */ + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + /** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Additional properties describing a `Tool` to clients. + * + * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on `ToolAnnotations` + * received from untrusted servers. + */ + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + /** + * Execution-related properties for a tool. + */ + const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + /** + * Definition for a tool the client can call. + */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the client to request a list of tools the server has. + */ + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); + /** + * The server's response to a tool call. + */ + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_record(schemas_string(), unknown()).optional(), + isError: schemas_boolean().optional() + }); + /** + * Parameters for a `tools/call` request. + */ + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Used by the client to invoke a tool provided by the server. + */ + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + /** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * The severity of a log message. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * Parameters for a `logging/setLevel` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + /** + * A request from the client to the server, to enable or adjust logging. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + /** + * Parameters for a `notifications/message` notification. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + /** + * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + /** + * Hints to use for model selection. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + /** + * Controls tool usage behavior in sampling requests. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + /** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via `ToolUseContent`. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_object({}).loose().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + /** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** + * Describes a message issued to or received from an LLM API. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Parameters for a `sampling/createMessage` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request when tools were provided. + * This version supports array content for tool use flows. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) + }); + /** + * Primitive schema definition for boolean fields. + */ + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + /** + * Primitive schema definition for string fields. + */ + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + /** + * Primitive schema definition for number fields. + */ + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + /** + * Schema for single-selection enumeration without display titles for options. + */ + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + /** + * Schema for single-selection enumeration with display titles for each option. + */ + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + /** + * Use {@linkcode TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + */ + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + /** + * Schema for multiple-selection enumeration without display titles for options. + */ + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Schema for multiple-selection enumeration with display titles for each option. + */ + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Combined schema for multiple-selection enumeration + */ + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + /** + * Primitive schema definition for enum fields. + */ + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + /** + * Union of all primitive schema definitions. + */ + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + /** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + /** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() + }); + /** + * The parameters for a request to elicit additional information from the user via the client. + */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); + /** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + /** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) + }); + /** + * A reference to a resource or resource template definition. + */ + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + /** + * Identifies a prompt. + */ + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + /** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }); + /** + * A request from the client to the server, to ask for completion options. + */ + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) + }) }); + /** + * Represents a root directory or file that the server can operate on. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the server to request a list of root URIs from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + /** + * The client's response to a `roots/list` request from the server. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); + /** + * A notification from the client to the server, informing it that the list of roots has changed. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Task creation parameters, used to ask that the server create a task to represent a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskCreationParamsSchema$1 = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() + }); + /** + * The status of a task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusSchema$1 = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + /** + * A pollable state object associated with a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskSchema$1 = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema$1, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) + }); + /** + * Result returned when a task is created, containing the task data wrapped in a `task` field. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + /** + * Parameters for task status notification. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + /** + * A notification sent when a task's status changes. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + /** + * A request to get the state of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a {@linkcode GetTaskRequest | tasks/get} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + /** + * A request to get the result of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a `tasks/result` request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. + * + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + /** + * A request to list tasks. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + /** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); + /** + * A request to cancel a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + RequestSchema: RequestSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + ResultSchema: ResultSchema$1, + RequestIdSchema: RequestIdSchema$1, + EmptyResultSchema: EmptyResultSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, + InitializeRequestSchema: InitializeRequestSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + InitializeResultSchema: InitializeResultSchema$1, + InitializedNotificationSchema: InitializedNotificationSchema$1, + PingRequestSchema: PingRequestSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, + PaginatedRequestSchema: PaginatedRequestSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + RoleSchema: RoleSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, + ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, + SubscribeRequestSchema: SubscribeRequestSchema$1, + UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, + UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolExecutionSchema: ToolExecutionSchema$1, + ToolSchema: ToolSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, + CallToolRequestSchema: CallToolRequestSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, + SetLevelRequestSchema: SetLevelRequestSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingContentSchema: SamplingContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, + ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + RootSchema: RootSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, + TaskCreationParamsSchema: TaskCreationParamsSchema$1, + TaskStatusSchema: TaskStatusSchema$1, + TaskSchema: TaskSchema$1, + CreateTaskResultSchema: CreateTaskResultSchema$1, + TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, + TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, + GetTaskRequestSchema: GetTaskRequestSchema$1, + GetTaskResultSchema: GetTaskResultSchema$1, + GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, + GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, + ListTasksRequestSchema: ListTasksRequestSchema$1, + ListTasksResultSchema: ListTasksResultSchema$1, + CancelTaskRequestSchema: CancelTaskRequestSchema$1, + CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), + ClientRequestSchema: schemas_union([ + PingRequestSchema$1, + InitializeRequestSchema$1, + CompleteRequestSchema$1, + SetLevelRequestSchema$1, + GetPromptRequestSchema$1, + ListPromptsRequestSchema$1, + ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema$1, + SubscribeRequestSchema$1, + UnsubscribeRequestSchema$1, + CallToolRequestSchema$1, + ListToolsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ClientNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: schemas_union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: schemas_union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: schemas_union([ + EmptyResultSchema$1, + InitializeResultSchema$1, + CompleteResultSchema$1, + GetPromptResultSchema$1, + ListPromptsResultSchema$1, + ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema$1, + CallToolResultSchema$1, + ListToolsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + CallToolResultWireSchema: unknown().superRefine((value, ctx) => { + if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { + ctx.addIssue({ + code: "custom", + message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +let memo$1; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2025() { + return memo$1 ??= build$1(); +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts +/** +* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). +* +* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON +* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, +* so when an era-blind handler advertises a non-object root, the 2025 codec's +* `encodeResult('tools/list', …)` projects it down to +* `{type:'object', properties:{result:}, required:['result']}`, and +* `projectCallToolResult` wraps the matching `structuredContent` as +* `{result:}`. The 2026 codec's projections are the identity. +* +* These helpers are wire-layer property — they exist so the projection can +* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} +* and never be re-derived in shared/ or server-side code. +*/ +/** +* Whether a JSON Schema's root is non-object: either an explicit non-object +* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless +* roots that the schema-conversion layer can prove are objects are stamped +* `type:'object'` upstream, so they reach this predicate as object roots. +*/ +function isNonObjectJsonSchemaRoot(json) { + return json["type"] !== "object"; +} +/** +* Keyword-position keys whose values are instance data (not subschemas). A +* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to +* rewrite. Only consulted when the current object is in keyword position — +* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name +* position whose value IS a subschema and is recursed into. +*/ +const REF_REWRITE_DATA_POSITION_KEYS = new Set([ + "const", + "enum", + "default", + "examples" +]); +/** +* Keyword-position keys whose value is a name→subschema map. Entries inside +* such a map are in NAME position: their keys are author-chosen property +* names (which may collide with JSON Schema keywords), their values are +* subschemas to recurse into. +*/ +const REF_REWRITE_NAME_MAP_KEYS = new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies" +]); +/** +* Whether a subtree's `$id` establishes a new resolution base. A fragment-only +* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not +* change the RFC 3986 base URI — same-document pointers inside still resolve +* against the document root and must be rewritten. +*/ +function establishesNewBase(id) { + return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); +} +/** +* Wrap a non-object output schema in the 2025-era envelope: +* `{type:'object', properties:{result:}, required:['result']}`. +* +* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema +* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) +* are rewritten to account for the new `#/properties/result` root: bare `#` → +* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs +* (anything not starting with `#`) are left untouched. +* +* The rewrite is position-aware: data-valued keywords +* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended +* into; the same names appearing as property names under +* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ +* `dependencies` ARE descended into (they're subschemas). The rewrite is also +* `$id`-scoped: if the natural root carries a base-establishing `$id` no +* pointer is rewritten (same-document refs inside resolve against the embedded +* `$id` base, not the wrapper root), and any subtree that establishes its own +* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, +* draft-07's anchor spelling) does not establish a base and IS descended into. +*/ +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (establishesNewBase(natural["$id"])) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; + const rewriteRefs = (node, parentIsNameMap) => { + if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); + if (node === null || typeof node !== "object") return node; + if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; + const out = {}; + let convertedRecursion = false; + for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); + else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; + else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; + else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; + else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); + else out[k] = rewriteRefs(v, false); + if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; + else out["$ref"] = "#/properties/result"; + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/registry.ts +const requestMethodKeys$1 = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "tasks/get": null, + "tasks/result": null, + "tasks/list": null, + "tasks/cancel": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +const notificationMethodKeys$1 = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/initialized": null, + "notifications/roots/list_changed": null, + "notifications/tasks/status": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/elicitation/complete": null +}; +const resultMethodKeys = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +let maps$1; +function registryMaps() { + if (maps$1) return maps$1; + const s = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + "completion/complete": s.CompleteRequestSchema, + "logging/setLevel": s.SetLevelRequestSchema, + "prompts/get": s.GetPromptRequestSchema, + "prompts/list": s.ListPromptsRequestSchema, + "resources/list": s.ListResourcesRequestSchema, + "resources/templates/list": s.ListResourceTemplatesRequestSchema, + "resources/read": s.ReadResourceRequestSchema, + "resources/subscribe": s.SubscribeRequestSchema, + "resources/unsubscribe": s.UnsubscribeRequestSchema, + "tools/call": s.CallToolRequestSchema, + "tools/list": s.ListToolsRequestSchema, + "tasks/get": s.GetTaskRequestSchema, + "tasks/result": s.GetTaskPayloadRequestSchema, + "tasks/list": s.ListTasksRequestSchema, + "tasks/cancel": s.CancelTaskRequestSchema, + "sampling/createMessage": s.CreateMessageRequestSchema, + "elicitation/create": s.ElicitRequestSchema, + "roots/list": s.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s.CancelledNotificationSchema, + "notifications/progress": s.ProgressNotificationSchema, + "notifications/initialized": s.InitializedNotificationSchema, + "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, + "notifications/tasks/status": s.TaskStatusNotificationSchema, + "notifications/message": s.LoggingMessageNotificationSchema, + "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + "completion/complete": s.CompleteResultSchema, + "logging/setLevel": s.EmptyResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "resources/subscribe": s.EmptyResultSchema, + "resources/unsubscribe": s.EmptyResultSchema, + "tools/call": s.CallToolResultWireSchema, + "tools/list": s.ListToolsResultSchema, + "sampling/createMessage": s.CreateMessageResultWithToolsSchema, + "elicitation/create": s.ElicitResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps$1; +} +/** +* Forces the lazy registry maps (and, through them, the era's schema memo). +* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmRegistryMaps2025() { + registryMaps(); +} +/** The 2025-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +/** The 2025-era notification-method set. */ +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ +function hasResultMethod(method) { + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); +} +function getResultSchema(method) { + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; +} +function getRequestSchema(method) { + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; +} +function getNotificationSchema(method) { + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2025RequestMethods = Object.keys(requestMethodKeys$1); +const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/codec.ts +function isPlainObject$6(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState$1(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" +}; +/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ +function toolNeedsLegacyWrap(t) { + return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ +function toNeutralResult(value) { + return value; +} +const rev2025Codec = { + era: "2025-11-25", + hasRequestMethod: hasRequestMethod2025, + hasNotificationMethod: hasNotificationMethod2025, + validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), + validateResult: (method, raw) => triState$1(getResultSchema(method), raw), + validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), + hasInputRequestMethod: () => false, + validateInputRequest: () => NOT_IN_ERA$1, + validateInputResponse: () => NOT_IN_ERA$1, + samplingResultVariant: ((hasTools, raw) => { + const s = buildSchemas2025(); + return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }), + outboundEnvelope: (_material) => void 0, + validateEnvelopeMeta: (_meta) => [], + projectCallToolResult(result, advertisedOutputSchema) { + const withText = appendTextFallbackForNonObject(result); + const sc = withText.structuredContent; + if (sc === void 0) return withText; + const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); + const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); + if (!valueIsNonObject && !schemaWrapped) return withText; + return { + ...withText, + structuredContent: { result: sc } + }; + }, + decodeResult(_method, raw) { + if (isPlainObject$6(raw) && "resultType" in raw) { + const stripped = { ...raw }; + delete stripped["resultType"]; + return { + kind: "complete", + result: toNeutralResult(stripped) + }; + } + return { + kind: "complete", + result: toNeutralResult(raw) + }; + }, + encodeResult(method, result) { + if (method !== "tools/list") return result; + const tools = result.tools; + if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; + return { + ...result, + tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { + ...t, + outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) + } : t) + }; + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope: (_material) => void 0 +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts +/** +* 2026-era wire schemas (protocol revision 2026-07-28). +* +* Fully self-contained — no runtime imports from types/schemas.ts. The +* neutral types/schemas.ts layer is the public-API superset and is free to +* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN +* against the 2026-07-28 anchor. Every era-shared building block (content +* blocks, resources, prompts, capabilities, notifications, …) that the wire +* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at +* the point this revision was sealed, dependencies first. The only cross-layer +* dependency is `import type { JSONObject, JSONValue }` from the neutral types +* barrel — pure structural type aliases with no parse behavior. +* +* This module is the only place the per-request `_meta` envelope is modeled. +* The envelope is wire-only vocabulary: the protocol layer lifts it off +* inbound requests before any handler runs and surfaces it at +* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at +* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc +* deferral ("enforced per request at dispatch time, not here") is now +* discharged by that codec step. +* +* No 2025-era traffic ever touches this module, so requiredness here is +* bare and spec-exact (the shared-schema `.catch` hazards do not apply). +* +* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed +* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the +* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from +* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result +* body to the new `ResultMetaObject` key +* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). +* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is +* modeled anywhere (per ruling: the final revision is the only 2026-07-28). +*/ +function build() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * The severity of a log message. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = schemas_object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = schemas_object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + /** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28: the protocol version governing the request, the client implementation + * info, and the client's capabilities — declared per request rather than once at + * initialization — plus the optional log-level opt-in. + * + * This schema models the complete envelope on its own (loose: foreign keys + * pass through - the lift extracts exactly the reserved keys, so enforcement + * never sees extension material). Requiredness is enforced per request at + * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + */ + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: looseObject({ + $schema: schemas_string().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string(), + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era sampling content union (composes the forked tool-result shape). */ + const SamplingMessageContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** 2026-era SamplingMessage (anchor-exact: single block or array). */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** Open union per the anchor: 'complete' | 'input_required' | string. */ + const ResultTypeSchema = schemas_string(); + /** + * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): + * loose, with the serverInfo key typed when present; the outbound stamp + * is the encode contract's `stampServerInfoMeta` step. + */ + const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); + const wireMeta = ResultMetaSchema.optional(); + function wireResult(shape) { + return looseObject({ + _meta: wireMeta, + resultType: ResultTypeSchema.default("complete"), + ...shape + }); + } + const ResultSchema$1 = wireResult({}); + const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); + const CallToolResultSchema$1 = wireResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }); + const ListToolsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }); + /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ + const CacheableResultSchema = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }); + /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ + const CreateMessageRequestParamsSchema$1 = schemas_object({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** 2026-era embedded sampling request (de-JSON-RPC'd). */ + const CreateMessageRequestSchema$1 = schemas_object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input + * requests do NOT carry the per-request `_meta` envelope on this revision — + * the anchor declares a bare optional `_meta` on `params`. + */ + const ListRootsRequestSchema$1 = schemas_object({ + method: literal("roots/list"), + params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() + }); + /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ + const CreateMessageResultSchema$1 = schemas_object({ + ...SamplingMessageSchema$1.shape, + model: schemas_string(), + stopReason: schemas_string().optional() + }); + /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ + const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); + /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ + const ElicitResultSchema$1 = schemas_object({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional() + }); + /** + * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed + * `elicitationId` (and the `notifications/elicitation/complete` channel it + * keyed) — the shared schema keeps the field because it is required on the + * frozen 2025-11-25 revision. + */ + const ElicitRequestURLParamsSchema$1 = schemas_object({ + mode: literal("url"), + message: schemas_string(), + url: schemas_string().url() + }); + /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ + const ElicitRequestSchema$1 = schemas_object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** A single embedded input request (one of the three demoted server→client requests). */ + const InputRequestSchema = schemas_union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ + const InputResponseSchema = schemas_union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + /** Map of embedded input requests, keyed by server-assigned identifiers. */ + const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); + /** Map of embedded input responses, keyed by the corresponding request identifiers. */ + const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); + /** + * The wire InputRequiredResult: `resultType: 'input_required'` plus at least + * one of `inputRequests` / `requestState` (the at-least-one rule is enforced + * at the server seam, not by this parse shape). + */ + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: schemas_string().optional() + }); + /** The retry-channel members carried by client-initiated requests on this revision. */ + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: schemas_string().optional() + }; + /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ + const InputResponseRequestParamsSchema = schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + /** Post-lift request `_meta` (progressToken + extension keys; loose). */ + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional(), + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; + const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); + const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); + const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); + const GetPromptRequestSchema$1 = wireRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: schemas_string(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + /** Anchor SubscriptionFilter (2026-only). */ + const SubscriptionFilterSchema$1 = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + /** + * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on + * the graceful-close result. Extends `ResultMetaObject` since spec PR + * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). + */ + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + /** + * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` + * response signalling that the subscription has ended gracefully (server + * shutdown). An abrupt transport close carries no response — the client treats + * stream-close-without-result as a disconnect. + */ + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }), + "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), + "resources/list": dispatchRequest("resources/list", paginatedParamsShape), + "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), + "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + /** Dispatch (post-lift) result schemas, keyed by method — what the funnel + * validates AFTER `decodeResult` consumed `resultType`. */ + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }), + "tools/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + /** + * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the + * subscriptions/listen demux key typed when present. Only the anchor-exact + * SHAPE is modeled here — listen delivery itself (filter gating, demux, + * teardown) is #14 scope and not implemented by this module. + */ + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ + const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ + method: literal("notifications/subscriptions/acknowledged"), + params: schemas_object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + /** + * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` + * is REQUIRED on this revision — the shared schema keeps it optional because + * the frozen 2025-11-25 shape declares it optional (task cancellation goes + * through `tasks/cancel` there). Requiredness is bare because no 2025-era + * traffic touches this module. + */ + const CancelledNotificationParamsSchema$1 = schemas_object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: schemas_string().optional() + }); + /** 2026-era `notifications/cancelled` (see the params fork above). */ + const CancelledNotificationSchema$1 = schemas_object({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const notificationSchemas2026 = { + "notifications/cancelled": CancelledNotificationSchema$1, + "notifications/progress": ProgressNotificationSchema$1, + "notifications/message": LoggingMessageNotificationSchema$1, + "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, + "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, + "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, + "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, + "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 + }; + const wireResultResponse = (result) => schemas_object({ + jsonrpc: literal("2.0"), + id: schemas_union([schemas_string(), schemas_number().int()]), + result + }).strict(); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + RequestIdSchema: RequestIdSchema$1, + RoleSchema: RoleSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + RootSchema: RootSchema$1, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema: ToolSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + ResultTypeSchema, + ResultMetaSchema, + ResultSchema: ResultSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + CacheableResultSchema, + DiscoverResultSchema: DiscoverResultSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema: CallToolRequestSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + DiscoverRequestSchema: DiscoverRequestSchema$1, + SubscriptionFilterSchema: SubscriptionFilterSchema$1, + SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, + SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, + SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + notificationSchemas2026, + JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), + CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +let src_CX2iR2pK_memo; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2026() { + return src_CX2iR2pK_memo ??= build(); +} + +//#endregion +//#region ../core-internal/src/shared/resultCacheHints.ts +/** +* The operations whose results are cacheable on the 2026-07-28 revision (the +* `CacheableResult` extenders). This list is closed: no other operation's +* result ever receives cache fields from the SDK. +*/ +const CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" +]; +/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +/** +* The symbol-keyed carrier for a configured cache hint on a result object. +* Symbol properties are invisible to JSON serialization, so the carrier can be +* attached era-blind: only the 2026-era encode seam consumes it. +*/ +const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); +/** +* Attaches a configured cache hint to a result as the encode-time fallback. +* Returns the result unchanged when there is nothing to attach. When a more +* specific hint is already attached, the two hints are combined per field +* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the +* per-registration hint attached by the feature layer keeps every field it +* sets, and the server-level per-operation hint only fills the fields the +* more specific hint leaves unset. +*/ +function attachCacheHintFallback(result, hint) { + if (hint === void 0) return result; + const attached = result[RESULT_CACHE_HINT_FALLBACK]; + if (attached === void 0) return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: hint + }; + const merged = {}; + const ttlMs = attached.ttlMs ?? hint.ttlMs; + if (ttlMs !== void 0) merged.ttlMs = ttlMs; + const cacheScope = attached.cacheScope ?? hint.cacheScope; + if (cacheScope !== void 0) merged.cacheScope = cacheScope; + return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: merged + }; +} +/** Reads the configured cache-hint fallback attached to a result, if any. */ +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +/** +* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe +* integers are required because the wire schemas validate `ttlMs` as an +* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value +* outside that range is treated as invalid here so it falls through to the +* next author instead of being emitted and rejected downstream. +*/ +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +/** Whether a value is a valid `cacheScope`. */ +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +/** +* Validates a configured cache hint at configuration time. Throws a +* `RangeError` naming the offending field, so misconfiguration fails at +* startup/registration rather than silently degrading at encode time. +*/ +function assertValidCacheHint(hint, context) { + if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); + if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); +} + +//#endregion +//#region ../core-internal/src/types/enums.ts +/** +* Error codes for protocol errors that cross the wire as JSON-RPC error responses. +* These follow the JSON-RPC specification and MCP-specific extensions. +*/ +let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { + ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; + /** + * Resource not found. + * + * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` + * misses answer `-32602` (Invalid Params) on every protocol revision per + * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to + * `-32602` at the era encode seam. The member stays importable so clients + * can recognise `-32002` from peers built on earlier SDK releases (the + * spec's "clients SHOULD also accept `-32002`" backwards-compatibility + * clause). Throw `ResourceNotFoundError` instead. + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + /** + * Processing the request requires a capability the client did not declare + * in the request's `clientCapabilities` (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + /** + * The request's protocol version is unknown to the server or unsupported + * by it (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; +}({}); + +//#endregion +//#region ../core-internal/src/types/errors.ts +/** +* Protocol errors are JSON-RPC errors that cross the wire as error responses. +* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. +* +* `instanceof` on this class (and its subclasses) is brand-matched, so it works +* across separately bundled copies of the SDK — e.g. an error constructed by +* `@modelcontextprotocol/client` matches the class re-exported by +* `@modelcontextprotocol/server` in the same process. +*/ +var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "ProtocolError"; + stampErrorBrands(this, new.target); + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); + } + return new ProtocolError(code, message, data); + } +}; +/** +* Error type for a `resources/read` miss: the requested resource does not +* exist. The wire code is `-32602` (Invalid Params) on every protocol +* revision — the spec MUST for revision 2026-07-28, and the value the v1.x +* SDK has always emitted on earlier revisions. The error data echoes the +* requested URI. +* +* Recognise this error by checking `error.data` is exactly `{ uri: string }` +* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; +* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also +* accept `-32002` as resource not found — earlier SDK builds emitted that +* code, and {@linkcode ProtocolError.fromError} reconstructs this class for +* either code **when `error.data` carries `uri`** (a bare `-32002` without +* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks +* are brand-matched and work across separately bundled copies of the SDK. +*/ +var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message = `Resource not found: ${uri}`) { + super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } +}; +/** +* Specialized error type when a tool requires a URL mode elicitation. +* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. +*/ +var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +/** +* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol +* revision 2026-07-28): the request's protocol version is unknown to the server or +* unsupported by it. +* +* The error data lists the protocol versions the receiver supports (`supported`), +* so the sender can choose a mutually supported version and retry, and echoes the +* version that was requested (`requested`). +*/ +var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message = `Unsupported protocol version: ${data.requested}`) { + super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } +}; +/** +* Error type for the `-32021` MissingRequiredClientCapability protocol error +* (protocol revision 2026-07-28): processing the request requires a capability +* the client did not declare in the request's `clientCapabilities`. +* +* The error data lists the missing capabilities (`requiredCapabilities`) in +* the `ClientCapabilities` shape, so the client can see exactly what it would +* have to declare for the request to be served. On HTTP, the response status +* is `400 Bad Request`. +* +* Recognize this error by its code and `data.requiredCapabilities`, or by +* `instanceof` — checks are brand-matched and work across separately bundled +* copies of the SDK. +*/ +var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); + } + /** + * The capabilities the server requires from the client to process the + * request (only the missing capabilities are listed). + */ + get requiredCapabilities() { + return this.data.requiredCapabilities; + } +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts +/** The default cache policy when neither the handler nor configuration provides one. */ +const DEFAULT_CACHE_TTL_MS = 0; +const DEFAULT_CACHE_SCOPE = "private"; +/** +* Request methods whose spec result vocabulary goes beyond `'complete'` on the +* 2026-07-28 revision: their results may be `input_required` (multi +* round-trip requests), so a handler-provided `resultType` passes through the +* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits +* a JSON-RPC result — termination is stream close (HTTP) or +* `notifications/cancelled` (stdio) per the spec. +*/ +const EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" +]; +/** +* Step 1 of the encode contract: ensure the outbound result carries the +* required `resultType` discriminator. +* +* - No handler-provided value → stamp `'complete'`. +* - Handler-provided `'complete'` → kept as-is. +* - Handler-provided non-`'complete'` value on a method whose vocabulary +* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. +* The value is forwarded verbatim — the wire vocabulary is an open union and +* the SDK does not validate the string, so emitting a `resultType` the +* negotiated revision does not define is the handler author's +* responsibility. +* - Handler-provided non-`'complete'` value on any other method → internal +* error (loud): the value would be mis-typed on the wire, and silently +* rewriting it would hide a server bug. +*/ +function stampResultType(method, result) { + const provided = result["resultType"]; + if (provided === void 0) return { + ...result, + resultType: "complete" + }; + if (provided === "complete") return result; + if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +/** +* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields +* on cacheable results. +* +* Applies only when the (post-stamp) `resultType` is `'complete'` and the +* method is one of the cacheable operations; everything else is returned +* untouched apart from removing the configured-hint carrier. Field resolution +* is per field, most specific author first: a valid handler-returned value, +* then the configured cache hint attached by the server layer, then the +* defaults. Handler-returned values are validated at encode time (`ttlMs` +* must be a non-negative integer, `cacheScope` must be `'public'` or +* `'private'`); invalid values are ignored rather than emitted. +*/ +function fillCacheFields(method, result) { + const fallback = cacheHintFallbackOf(result); + if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); + const provided = result; + const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); + const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); + const filled = { + ...provided, + ttlMs, + cacheScope + }; + delete filled[RESULT_CACHE_HINT_FALLBACK]; + return filled; +} +function isPlainObject$5(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Step 3 of the encode contract: stamp the server's identity into the +* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: +* servers SHOULD include it on every response). +* +* - No `serverInfo` supplied (a client instance, or a hand-constructed +* protocol object) → identity function. +* - The result's `_meta` already carries the key → kept as-is (the handler +* is the more specific author; mirrors the cache-fill resolution order). +* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: +* the stamp never rewrites handler material, and the malformed value fails +* loudly at the peer instead of being silently replaced here. +* - Otherwise → the key is added, preserving any other `_meta` entries. +* +* Runs for every result regardless of `resultType`: the anchor types +* `Result._meta` as `ResultMetaObject` on all results, `input_required` +* included. +*/ +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta = result["_meta"]; + if (meta === void 0) return { + ...result, + _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$5(meta)) return result; + if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta, + [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo + } + }; +} +function resolveTtlMs(fallback) { + return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; +} +function resolveCacheScope(fallback) { + return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; +} +function stripCacheHintFallback(result) { + const copy = { ...result }; + delete copy[RESULT_CACHE_HINT_FALLBACK]; + return copy; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts +/** +* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 +* multi round-trip requests), dispatch view. +* +* The three former server→client wire requests (`elicitation/create`, +* `sampling/createMessage`, `roots/list`) are NOT wire request methods on +* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an +* `input_required` result. The multi-round-trip driver dispatches those +* embedded payloads to the client's registered handlers through the normal +* handler machinery, and these are the schemas that dispatch parses them +* with: lenient where the anchor's wire-true artifacts are strict (an +* embedded request never carries the per-request `_meta` envelope), exact +* where the vocabulary forks (the sampling shapes compose the forked +* SamplingMessage/Tool payloads). +* +* Registry membership is intentionally NOT granted here — these methods stay +* absent from the 2026-era request registry (a peer sending one as a wire +* request still gets −32601 by absence). Only the codec's +* `inputRequestSchema`/`inputResponseSchema` accessors expose them. +*/ +/** The embedded input-request methods of the 2026-07-28 revision. */ +const INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" +]; +let maps; +function inputSchemaMaps() { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + "elicitation/create": schemas_object({ + method: literal("elicitation/create"), + params: s.ElicitRequestParamsSchema + }), + "sampling/createMessage": schemas_object({ + method: literal("sampling/createMessage"), + params: s.CreateMessageRequestParamsSchema + }), + "roots/list": schemas_object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s.ElicitResultSchema, + "sampling/createMessage": s.CreateMessageResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps; +} +/** +* Forces the lazy embedded-request maps (and, through them, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmInputSchemaMaps2026() { + inputSchemaMaps(); +} +function isInputRequestMethod2026(method) { + return INPUT_REQUEST_METHODS_2026.includes(method); +} +function getInputRequestSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; +} +function getInputResponseSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/registry.ts +const requestMethodKeys = { + "tools/call": null, + "tools/list": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "completion/complete": null, + "server/discover": null, + "subscriptions/listen": null +}; +const notificationMethodKeys = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/subscriptions/acknowledged": null +}; +/** The 2026-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +/** The 2026-era notification-method set. */ +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +/** Result-map membership (same key set as the request map on this era). */ +function hasResultMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function getRequestSchema2026(method) { + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; +} +function getResultSchema2026(method) { + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; +} +function getNotificationSchema2026(method) { + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2026RequestMethods = Object.keys(requestMethodKeys); +const rev2026NotificationMethods = Object.keys(notificationMethodKeys); + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/codec.ts +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA = { + ok: false, + reason: "not-in-era" +}; +/** +* The reserved `_meta` keys an envelope must carry on this era (in reporting +* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a +* request without it is accepted (a present-but-malformed value still fails +* the envelope schema parse below). +*/ +const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; +/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ +function enforceDeletedFields(method, result) { + let next = result; + let copied = false; + const copy = () => { + if (!copied) { + next = { ...next }; + copied = true; + } + return next; + }; + const tools = result.tools; + if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { + if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; + const rest = { ...tool }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$4(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy().capabilities = rest; + } + return next; +} +const rev2026Codec = { + era: "2026-07-28", + hasRequestMethod: hasRequestMethod2026, + hasNotificationMethod: hasNotificationMethod2026, + hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, + validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), + validateResult: (method, raw) => triState(getResultSchema2026(method), raw), + validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), + validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), + validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), + samplingResultVariant: () => NOT_IN_ERA, + outboundEnvelope(material) { + return { + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); + if (!parsed.success) for (const issue of parsed.error.issues) { + const path = issue.path.map(String); + const key = path.length > 0 ? path.join(".") : "_meta"; + if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; + issues.push({ + key, + problem: issue.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$4(raw)) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { + method, + violation: "input-required-missing-both" + }) + }; + return { + kind: "input_required", + inputRequests, + ...typeof requestState === "string" && { requestState } + }; + } + if (rawResultType !== "complete") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { + resultType: rawResultType, + method + }) + }; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; + if (wireSchema !== void 0) { + const parsed = wireSchema.safeParse(raw); + if (!parsed.success) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) + }; + } + const lifted = { ...raw }; + delete lifted["resultType"]; + return { + kind: "complete", + result: lifted + }; + }, + encodeResult(method, result, serverInfo) { + return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope(material) { + if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); + if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; + } +}; +/** Wire-true result wrappers consulted by decode step 2, keyed by method — +* built once through the era's schema memo on the first decode. */ +let wireResultSchemasMemo; +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s.CallToolResultSchema, + "tools/list": s.ListToolsResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "completion/complete": s.CompleteResultSchema, + "server/discover": s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +/** +* Forces the lazy wire-result wrapper map (and, through it, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. +*/ +function warmWireResultSchemas2026() { + getWireResultSchemas(); +} + +//#endregion +//#region ../core-internal/src/wire/codec.ts +/** +* The modern wire revision literal. Internal only — deliberately NOT a public +* constant (G-D2-4: no public modern-version constant ships before era-aware +* list semantics exist). +*/ +const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; +/** +* Era resolution, many-to-one (Q1-SD1): every modern-era revision +* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five +* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era +* codec (the DV-13 default posture — hand-constructed instances and +* unclassified traffic are legacy-era). This is the same era predicate the +* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern +* revision other than the literal '2026-07-28' must still resolve modern. +*/ +function src_CX2iR2pK_codecForVersion(version) { + return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; +} +/** +* The wire era an edge classification names (Q2 — produced at the +* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no +* longer resolves a codec FROM the classification: era is instance state, and +* a classified inbound message is VALIDATED against the instance era — a +* mismatch is an entry/routing error, never a per-message era switch. The +* exact `revision` wins over the coarse era flag when both are present. +*/ +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +/** +* The derived spec-method universe: the union of every codec registry. A +* method in this set is era-gated at dispatch and send time; a method outside +* it is a consumer-owned extension method (era-blind, schema-explicit). +* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS +* table class is exactly what registry membership replaces). +*/ +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); +} +const ALL_CODECS = [rev2025Codec, rev2026Codec]; + +//#endregion +//#region ../core-internal/src/shared/envelope.ts +/** +* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). +* +* Pure, value-returning helpers used by the inbound HTTP classifier +* (`classifyInboundRequest`): claim detection and envelope validation with +* self-identifying issues. The envelope schema itself stays the wire layer's +* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps +* its outcomes into the shapes the validation ladder emits. +* +* Claim detection is deliberately narrow: a message claims the 2026-07-28 +* envelope mechanism if and only if the reserved protocol-version `_meta` key +* is present in `params._meta`. Other reserved keys (client info, client +* capabilities, log level), a bare `progressToken`, or unrelated keys under +* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their +* own — but once the claim key is present, a malformed envelope is a +* validation error, never a silent fall back to legacy handling. +* +* The wire-exact envelope schema, the required-key set, and the per-key issue +* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). +* This module never reaches into a per-revision wire module directly. +*/ +function isPlainObject$3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** The `_meta` object of a message's params, when present. */ +function src_CX2iR2pK_requestMetaOf(params) { + if (!isPlainObject$3(params)) return void 0; + const meta = params["_meta"]; + return isPlainObject$3(meta) ? meta : void 0; +} +/** +* Whether a message's params carry the per-request envelope claim: the +* reserved protocol-version `_meta` key is present (regardless of whether the +* rest of the envelope is valid — validation is a separate, later step). +*/ +function src_CX2iR2pK_hasEnvelopeClaim(params) { + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; +} +/** +* The protocol version named by a message's envelope claim, when the claim is +* present and carries a string value. A present claim with a non-string value +* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a +* validation issue instead of a version. +*/ +function src_CX2iR2pK_envelopeClaimVersion(params) { + const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; + return typeof value === "string" ? value : void 0; +} +/** +* Validates a request's `_meta` object as a 2026-07-28 per-request envelope +* and reports problems as self-identifying issues (which key, what problem). +* +* Returns an empty array when the envelope is valid. Missing required keys are +* reported first (as `problem: 'missing'`), then schema violations inside +* present keys, in a stable order. +*/ +function src_CX2iR2pK_validateEnvelopeMeta(meta) { + return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); +} + +//#endregion +//#region ../core-internal/src/types/schemas.ts +var schemas_exports = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, + CancelTaskRequestSchema: () => CancelTaskRequestSchema, + CancelTaskResultSchema: () => CancelTaskResultSchema, + CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, + CancelledNotificationSchema: () => CancelledNotificationSchema, + ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, + ClientNotificationSchema: () => ClientNotificationSchema, + ClientRequestSchema: () => ClientRequestSchema, + ClientResultSchema: () => ClientResultSchema, + ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, + CompleteRequestSchema: () => CompleteRequestSchema, + CompleteResultSchema: () => CompleteResultSchema, + ContentBlockSchema: () => ContentBlockSchema, + CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, + CreateMessageRequestSchema: () => CreateMessageRequestSchema, + CreateMessageResultSchema: () => CreateMessageResultSchema, + CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, + CreateTaskResultSchema: () => CreateTaskResultSchema, + CursorSchema: () => CursorSchema, + DiscoverRequestSchema: () => DiscoverRequestSchema, + DiscoverResultSchema: () => DiscoverResultSchema, + ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, + ElicitRequestSchema: () => ElicitRequestSchema, + ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, + ElicitResultSchema: () => ElicitResultSchema, + ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, + EmbeddedResourceSchema: () => EmbeddedResourceSchema, + EmptyResultSchema: () => EmptyResultSchema, + EnumSchemaSchema: () => EnumSchemaSchema, + GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, + GetPromptRequestSchema: () => GetPromptRequestSchema, + GetPromptResultSchema: () => GetPromptResultSchema, + GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, + GetTaskRequestSchema: () => GetTaskRequestSchema, + GetTaskResultSchema: () => GetTaskResultSchema, + IconSchema: () => IconSchema, + IconsSchema: () => IconsSchema, + ImageContentSchema: () => ImageContentSchema, + ImplementationSchema: () => ImplementationSchema, + InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, + InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, + JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, + JSONValueSchema: () => JSONValueSchema, + LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, + ListPromptsRequestSchema: () => ListPromptsRequestSchema, + ListPromptsResultSchema: () => ListPromptsResultSchema, + ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, + ListResourcesRequestSchema: () => ListResourcesRequestSchema, + ListResourcesResultSchema: () => ListResourcesResultSchema, + ListRootsRequestSchema: () => ListRootsRequestSchema, + ListRootsResultSchema: () => ListRootsResultSchema, + ListTasksRequestSchema: () => ListTasksRequestSchema, + ListTasksResultSchema: () => ListTasksResultSchema, + ListToolsRequestSchema: () => ListToolsRequestSchema, + ListToolsResultSchema: () => ListToolsResultSchema, + LoggingLevelSchema: () => LoggingLevelSchema, + LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, + ModelHintSchema: () => ModelHintSchema, + ModelPreferencesSchema: () => ModelPreferencesSchema, + MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, + NotificationSchema: () => NotificationSchema, + NotificationsParamsSchema: () => NotificationsParamsSchema, + NumberSchemaSchema: () => NumberSchemaSchema, + PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, + PaginatedRequestSchema: () => PaginatedRequestSchema, + PaginatedResultSchema: () => PaginatedResultSchema, + PingRequestSchema: () => PingRequestSchema, + PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, + ProgressNotificationSchema: () => ProgressNotificationSchema, + ProgressSchema: () => ProgressSchema, + ProgressTokenSchema: () => ProgressTokenSchema, + PromptArgumentSchema: () => PromptArgumentSchema, + PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, + PromptMessageSchema: () => PromptMessageSchema, + PromptReferenceSchema: () => PromptReferenceSchema, + PromptSchema: () => PromptSchema, + ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, + ReadResourceRequestSchema: () => ReadResourceRequestSchema, + ReadResourceResultSchema: () => ReadResourceResultSchema, + RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, + RequestIdSchema: () => RequestIdSchema, + RequestMetaSchema: () => RequestMetaSchema, + RequestSchema: () => RequestSchema, + ResourceContentsSchema: () => ResourceContentsSchema, + ResourceLinkSchema: () => ResourceLinkSchema, + ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, + ResourceSchema: () => ResourceSchema, + ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, + ResourceTemplateSchema: () => ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, + ResultMetaObjectSchema: () => ResultMetaObjectSchema, + ResultSchema: () => ResultSchema, + RoleSchema: () => RoleSchema, + RootSchema: () => RootSchema, + RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, + SamplingContentSchema: () => SamplingContentSchema, + SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, + SamplingMessageSchema: () => SamplingMessageSchema, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, + ServerNotificationSchema: () => ServerNotificationSchema, + ServerRequestSchema: () => ServerRequestSchema, + ServerResultSchema: () => ServerResultSchema, + ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, + SetLevelRequestSchema: () => SetLevelRequestSchema, + SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, + StringSchemaSchema: () => StringSchemaSchema, + SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, + SubscribeRequestSchema: () => SubscribeRequestSchema, + SubscriptionFilterSchema: () => SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema: () => TaskCreationParamsSchema, + TaskMetadataSchema: () => TaskMetadataSchema, + TaskSchema: () => TaskSchema, + TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, + TaskStatusSchema: () => TaskStatusSchema, + TextContentSchema: () => TextContentSchema, + TextResourceContentsSchema: () => TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema: () => ToolAnnotationsSchema, + ToolChoiceSchema: () => ToolChoiceSchema, + ToolExecutionSchema: () => ToolExecutionSchema, + ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, + ToolResultContentSchema: () => ToolResultContentSchema, + ToolSchema: () => ToolSchema, + ToolUseContentSchema: () => ToolUseContentSchema, + UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema +}); + +//#endregion +//#region ../core-internal/src/types/guards.ts +/** +* Validates and parses an unknown value as a JSON-RPC message. +* +* Use this to validate incoming messages in custom transport implementations. +* Throws if the value does not conform to the JSON-RPC message schema. +* +* @param value - The value to validate (typically a parsed JSON object). +* @returns The validated {@linkcode JSONRPCMessage}. +* @throws If validation fails. +*/ +function parseJSONRPCMessage(value) { + return JSONRPCMessageSchema.parse(value); +} +const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. +*/ +const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode CallToolResult}. +* +* This is a consumer-side VALUE check against the neutral model, not a wire +* validator: a raw wire object that additionally carries wire-only members +* (e.g. `resultType`) still passes through the loose index signature. Use a +* transport-level parse to validate raw wire traffic. +* +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. +*/ +const isCallToolResult = (value) => { + if (typeof value !== "object" || value === null || value.content === void 0) return false; + return CallToolResultSchema.safeParse(value).success; +}; +/** +* Checks whether a value is an input-required result (protocol revision +* 2026-07-28): the multi-round-trip return shape discriminated by +* `resultType: 'input_required'`. +* +* This is a discriminator check, not a full validator — the at-least-one rule +* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` +* builder and re-checked by the server seam for hand-built values. +* +* @param value - The value to check. +* @returns True if the value carries the `input_required` discriminator. +*/ +const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; +/** +* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. +* +* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK +* runtime; kept importable for interoperability only. +*/ +const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); +} + +//#endregion +//#region ../core-internal/src/shared/mcpParamHeaders.ts +/** The fixed prefix every custom-parameter header carries. */ +const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; +/** The schema-extension property name a tool's `inputSchema` carries. */ +const X_MCP_HEADER_KEY = "x-mcp-header"; +/** +* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control +* characters (including CR/LF), and the listed delimiters. +*/ +const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +/** +* JSON Schema `type` values the spec admits on an `x-mcp-header` property. +* +* The spec text names `integer`, `string`, `boolean` and explicitly excludes +* `number`. The published conformance referee at the pinned release ships its +* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` +* parameters and expects the client to mirror them, so `number` is accepted +* here so that the conformance gate passes; the discrepancy is tracked +* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. +*/ +const PERMITTED_X_MCP_HEADER_TYPES = new Set([ + "string", + "integer", + "boolean", + "number" +]); +/** +* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations +* and validate every constraint the spec places on them. Returns either the +* collected declarations (possibly empty) or the first violated constraint. +* +* The walk descends through `properties` at any depth (the spec's "any nesting +* depth" clause). The static-reachability MUST is enforced as a structural +* sweep: every position the chain MUST NOT pass through (`items`/ +* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, +* `$defs`, `$ref` targets within `$defs`) is visited too, and an +* `x-mcp-header` found anywhere on that path invalidates the schema — "an +* annotation anywhere else makes the tool definition invalid". +*/ +function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { + const declarations = []; + const seenLower = /* @__PURE__ */ new Map(); + const visit = (node, path, reachable) => { + if (node === null || typeof node !== "object") return void 0; + const schema = node; + if (X_MCP_HEADER_KEY in schema) { + if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; + const raw = schema[X_MCP_HEADER_KEY]; + if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; + if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; + const type = typeof schema.type === "string" ? schema.type : void 0; + if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; + const lower = raw.toLowerCase(); + const prior = seenLower.get(lower); + if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; + seenLower.set(lower, raw); + declarations.push({ + path, + headerName: raw, + type + }); + } + const properties = schema.properties; + if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { + const fault$1 = visit(child, [...path, key], reachable); + if (fault$1 !== void 0) return fault$1; + } + for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { + const sub = schema[k]; + if (sub === void 0) continue; + const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; + for (const branch of branches) { + const fault$1 = visit(branch, [...path, `<${k}>`], false); + if (fault$1 !== void 0) return fault$1; + } + } + }; + const fault = visit(inputSchema, [], true); + return fault === void 0 ? { + valid: true, + declarations + } : { + valid: false, + reason: fault + }; +} +/** +* JSON Schema keywords whose subschemas the SEP-2243 static-reachability +* constraint excludes from the `properties`-only chain. An `x-mcp-header` +* found under any of these invalidates the tool definition. +*/ +const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "$defs", + "definitions" +]; +/** +* Subschema-carrying keywords whose value is a `name → subschema` object +* (not a single subschema or array of subschemas). The visit branches over +* `Object.values()` for these. +*/ +const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ + "patternProperties", + "dependentSchemas", + "$defs", + "definitions" +]); +function pathName(path) { + return path.length === 0 ? "" : path.join("."); +} +const BASE64_SENTINEL_PREFIX = "=?base64?"; +const BASE64_SENTINEL_SUFFIX = "?="; +const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; +/** +* Convert a primitive argument value to its string representation per the +* spec's type-conversion rules: strings pass through, integers and numbers +* become their decimal string, booleans become lowercase `'true'` / `'false'`. +* Non-finite numbers and integers outside the safe range are refused (the +* caller treats `undefined` as "do not emit a header for this value"). +*/ +function mcpParamPrimitiveToString(value) { + if (typeof value === "string") return value; + if (typeof value === "boolean") return value ? "true" : "false"; + if (typeof value === "number") { + if (!Number.isFinite(value)) return void 0; + if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; + return String(value); + } +} +function base64ToUtf8(b64) { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); +} +/** +* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, +* the payload is decoded as UTF-8; otherwise the value is returned as-is. +* Returns `undefined` when the sentinel is present but the payload is not +* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject +* such values. +*/ +function decodeMcpParamValue(value) { + if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; + const b64 = value.slice(9, value.length - 2); + if (!BASE64_CANONICAL.test(b64)) return void 0; + try { + return base64ToUtf8(b64); + } catch { + return; + } +} +function valueAtPath(root, path) { + let node = root; + for (const key of path) { + if (node === null || typeof node !== "object") return void 0; + node = node[key]; + } + return node; +} +/** +* The header/body comparison the server performs at tool-resolution time. +* +* For each `x-mcp-header` declaration on the named tool: when the body +* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be +* present and decode to an equal value; when the body value is `null` or +* absent the server MUST NOT expect the header (a present header is ignored). +* A sentinel-carrying header whose payload is not canonical Base64 / valid +* UTF-8 is rejected as invalid characters. +* +* Integer-typed declarations are compared numerically (the spec's SHOULD — +* `42.0` and `42` are equal); everything else is compared as decoded strings. +* +* Returns `undefined` when every check passes, or an +* {@linkcode InboundLadderRejection} carrying the same `-32020` +* (`HeaderMismatch`) shape the inbound classifier emits for the +* standard-header cross-checks — `400 Bad Request` with the disagreeing pair +* in `data.mismatch`. +*/ +function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { + for (const decl of declarations) { + const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; + const headerValue = headers.get(headerKey); + const bodyRaw = valueAtPath(args, decl.path); + if (bodyRaw === void 0 || bodyRaw === null) continue; + const bodyString = mcpParamPrimitiveToString(bodyRaw); + if (bodyString === void 0) continue; + if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); + const decoded = decodeMcpParamValue(headerValue); + if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); + if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); + } +} +/** +* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` +* disagreement. Same shape as the inbound classifier's standard-header +* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing +* pair, `settled: true`); only the rung differs because this check runs at the +* pre-dispatch step against a known tool's schema rather than at the edge. +*/ +function paramHeaderMismatchRejection(cell, header, body) { + return { + kind: "reject", + rung: "param-header-validation", + cell, + httpStatus: 400, + code: HEADER_MISMATCH_ERROR_CODE, + message: `Bad Request: the request headers and body disagree: ${body}`, + data: { mismatch: { + header, + body + } }, + settled: true + }; +} + +//#endregion +//#region ../core-internal/src/shared/inboundClassification.ts +/** +* Inbound HTTP request classification and the inbound validation ladder +* (protocol revision 2026-07-28). +* +* `classifyInboundRequest` is the body-primary era predicate for an HTTP +* entry that serves both protocol eras on one endpoint. It is evaluated +* exactly once, at the entry boundary, on the already-parsed request body: +* +* - `initialize` is a legacy-era request by definition (the modern era has no +* `initialize` handshake) — unless it carries a valid envelope claim naming +* a modern revision, in which case the claim wins and the request is +* classified like any other enveloped request (the modern era then answers +* it with method-not-found, exactly like every other method it does not +* define). +* - A request whose `params._meta` carries the reserved protocol-version key +* claims the per-request envelope mechanism and classifies into the era the +* named revision belongs to (a malformed envelope behind a present claim is +* a validation error, never a silent fall back to legacy handling). +* - A request without a claim is legacy-era traffic. +* - The `MCP-Protocol-Version` header is a cross-check only: it never +* upgrades or downgrades a body-derived classification, and a disagreement +* between header and body is an explicit ladder outcome. +* - Notifications carry no envelope claim of their own under the current +* spec, so for notification POSTs without a body claim the modern header is +* determinative; the `Mcp-Method` header is validated against the body when +* the message classifies modern and is never enforced on legacy traffic. +* A notification that does carry a claim is treated body-primary like a +* request, and a malformed claim is rejected the same way a request's +* malformed claim is — never silently resolved against the header. +* The notification-POST header cross-checks here are an SDK-defensive +* posture, not a spec requirement: the spec leaves header rules for posted +* notifications undefined (core client notifications do not occur over +* Streamable HTTP); applying the request rules symmetrically is what an +* ecosystem custom-notification POST expects, and the −32020 cells stay +* passing for them. +* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era +* session operations: the modern era is `POST`-only, so they are routed to +* legacy serving when it is configured and rejected otherwise. +* - Array (batch) bodies are classified element-wise: an array containing a +* modern-claiming or invalid element is rejected, an all-legacy array is +* legacy traffic unchanged, and a single-element array is still an array. +* +* The classifier returns plain values (it never throws and never touches a +* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection +* carrying the JSON-RPC error to emit and the HTTP status to emit it with. +* Legacy routing outcomes deliberately carry NO `MessageClassification` — +* legacy and hand-wired traffic is never classified, which keeps its +* dispatch behavior byte-identical to today's. +* +* Error codes for the modern-path rejection cells follow the published +* conformance suite (and the spec text it asserts): +* +* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header +* disagreeing with the body, or the `Mcp-Method` header disagreeing with the +* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. +* - A request whose protocol-version header names a modern revision but whose +* body carries no `_meta` envelope claim — including an envelope present but +* missing the required protocol-version key — is rejected with `-32602` +* (invalid params) naming the missing key(s), on HTTP 400. +* +* Should a future spec revision or conformance release change these +* assignments, the affected cells are re-derived against that release; the +* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark +* a cell provisional again while such a change is in flight. +*/ +/** +* The error code emitted for header/body cross-check mismatches: the +* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or +* with the body's classification), and the `Mcp-Method` header disagreeing +* with the body method. +* +* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 +* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted +* by the published conformance suite for header-validation failures. It has no +* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era +* wire vocabulary; the validation ladder is its only emitter. +*/ +const HEADER_MISMATCH_ERROR_CODE = -32020; +/** +* The inbound validation ladder, expressed as data rather than control flow. +* +* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the +* dispatch rungs are evaluated by the protocol layer once the classified +* message is injected into a per-request server instance (the era registry +* gate, the envelope requiredness check, and per-method params validation). +* The client-capability rung is evaluated by the HTTP entry itself, +* pre-dispatch, on the validated envelope the classifier produced — see that +* rung's rationale for the ordering caveat. The order is the precedence: a +* request that fails several rungs is answered by the earliest one. +*/ +const INBOUND_VALIDATION_LADDER = [ + { + rung: "http-method", + order: 1, + evaluatedAt: "edge", + codes: [-32e3], + conformance: [], + rationale: "The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read." + }, + { + rung: "jsonrpc-shape", + order: 2, + evaluatedAt: "edge", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest], + conformance: ["server-stateless"], + rationale: "The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic." + }, + { + rung: "era-classification", + order: 3, + evaluatedAt: "edge", + codes: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion], + conformance: [ + "server-stateless", + "http-header-validation", + "http-custom-header-server-validation" + ], + rationale: "Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions." + }, + { + rung: "envelope", + order: 4, + evaluatedAt: "edge", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." + }, + { + rung: "method-registry", + order: 5, + evaluatedAt: "dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." + }, + { + rung: "request-params", + order: 6, + evaluatedAt: "dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: [], + rationale: "Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table." + }, + { + rung: "standard-header-validation", + order: 7, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-header-validation"], + rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." + }, + { + rung: "param-header-validation", + order: 9, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." + } +]; +/** +* HTTP status for ladder-originated JSON-RPC error codes. +* +* Keyed on origin, not on the bare code: this table only applies to errors +* the ladder (or a pre-handler protocol gate) produced. Errors produced by +* request handlers — whatever their code — stay in-band on HTTP 200, and are +* never mapped to an HTTP status by this table; in particular `-32603` and +* domain-specific codes never become a blanket 500. The single exception is +* `MissingRequiredClientCapability` (-32021) — see +* {@linkcode httpStatusForErrorCode}. +* +* `-32602` (invalid params) deliberately has NO entry: the only invalid-params +* rejection that maps to HTTP 400 is the classifier's own envelope rung +* short-circuit, which carries its HTTP status directly. A dispatch- or +* handler-produced invalid-params error is always in-band. +*/ +const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { + [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, + [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, + [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 +}; +/** +* The HTTP status to answer a JSON-RPC error with, keyed on the error's +* origin. `in-band` errors (anything produced by a request handler) are +* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP +* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), +* whose 400 the spec mandates on the error itself with no origin condition, +* and which the SDK genuinely produces after dispatch (the `input_required` +* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` +* is NOT that peer's spec error and stays in-band like every other handler +* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. +* +* The per-request transport intentionally does NOT delegate to this function: +* its `?? 400` ladder fallback is only correct for entry-gate codes known to +* the table, and would wrongly map dispatch-window errors outside it (a +* window `-32602` must stay in-band on 200). The transport indexes the table +* directly; keep the two in agreement when editing either. +*/ +function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { + if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; + return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; +} +function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { + return { + kind: "reject", + rung, + cell, + httpStatus, + code: error.code, + message: error.message, + ...error.data !== void 0 && { data: error.data }, + settled + }; +} +function crossCheckMismatch(cell, header, body, rung = "era-classification") { + return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { + header, + body + } }), true); +} +/** +* The methods whose body carries a `params.name` / `params.uri` value the +* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 +* § Standard Request Headers, `Required For` column). +*/ +const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ + "tools/call": "name", + "prompts/get": "name", + "resources/read": "uri" +})); +/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ +function stripHttpOws(value) { + let start = 0; + while (start < value.length) { + const code = value.codePointAt(start); + if (code !== 9 && code !== 32) break; + start += 1; + } + let end = value.length; + while (end > start) { + const code = value.codePointAt(end - 1); + if (code !== 9 && code !== 32) break; + end -= 1; + } + return start === 0 && end === value.length ? value : value.slice(start, end); +} +/** +* SEP-2243 standard-header server-side validation, evaluated by the HTTP +* entry on a modern-classified request immediately after +* {@linkcode classifyInboundRequest} returns a modern route. +* +* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, +* `standard-header-validation` rung — the same shape +* {@linkcode classifyInboundRequest} already emits on the edge +* `era-classification` rung for the `MCP-Protocol-Version` and +* `Mcp-Method` *mismatch* cells) when: +* +* - the required `Mcp-Method` header is absent; +* - the required `Mcp-Name` header is absent on a `tools/call`, +* `prompts/get`, or `resources/read` request whose body carries the +* `params.name` / `params.uri` value the header mirrors; +* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or +* - the (decoded) `Mcp-Name` value disagrees with the body's +* `params.name` / `params.uri`. +* +* Returns `undefined` (pass) for notifications (the spec table reads +* "All requests"), for methods that have no `Mcp-Name` source, and when the +* headers agree with the body. Never enforced on legacy traffic — the entry +* only calls this on a modern route. +* +* Kept separate from {@linkcode classifyInboundRequest} so that a body-only +* call to the classifier (no headers passed) keeps routing a modern request +* unchanged: the classifier remains a pure body-primary router, and this +* function is the presence/`Mcp-Name` half of the standard-header rung the +* entry layers on top. +*/ +function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { + if (route.messageKind !== "request") return; + const method = route.message.method; + if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); + const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; + if (sourceField === void 0) return; + const sourceValue = route.message.params?.[sourceField]; + const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; + if (request.mcpNameHeader === void 0) { + if (bodyValue === void 0) return; + return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); + } + const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); + const decoded = decodeMcpParamValue(normalizedNameHeader); + if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); + if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function classificationForClaim(claimedVersion) { + if (claimedVersion === void 0) return { era: "modern" }; + return { + era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", + revision: claimedVersion + }; +} +/** +* Whether a request's params carry a per-request envelope claim that is both +* well-formed and names a modern protocol revision. +* +* Used by the `initialize` precedence rule: only such a claim overrides the +* `initialize` ⇒ legacy-handshake classification — a request carrying a valid +* modern envelope is a modern request regardless of its method name, and the +* modern era then answers `initialize` exactly like any other method it does +* not define (method-not-found). A malformed claim, or one naming a pre-2026 +* revision, keeps the legacy-handshake routing unchanged. +* +* Exported on the core internal barrel for the stdio serving entry, which +* applies the same precedence rule to a connection's opening message; not +* public API. +*/ +function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { + if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; +} +function classifyBatch(body) { + if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); + for (const element of body) { + if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); + if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); + } + return { + kind: "legacy", + reason: "batch" + }; +} +function classifyRequestBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { + if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); + const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "request", + message: body, + classification: classificationForClaim(claimedVersion) + }; + } + if (headerNamesModern) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); + const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; + return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); + } + return { + kind: "legacy", + reason: "no-claim", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +function classifyNotificationBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { + key: PROTOCOL_VERSION_META_KEY, + problem: "expected a protocol version string" + }; + return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); + } + if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + const classification = classificationForClaim(claimedVersion); + if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification + }; + } + if (headerNamesModern) { + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification: { + era: "modern", + revision: headerVersion + } + }; + } + return { + kind: "legacy", + reason: "notification", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +/** +* Classifies one inbound HTTP request for dual-era serving. +* +* The body-primary predicate, evaluated once at the entry boundary: see the +* module documentation for the rules. Returns a routing outcome (`legacy` or +* `modern`) or a ladder rejection; it never throws. +*/ +function src_CX2iR2pK_classifyInboundRequest(request) { + request = { + ...request, + ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, + ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, + ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } + }; + if (request.httpMethod.toUpperCase() !== "POST") return { + kind: "legacy", + reason: "http-method" + }; + const body = request.body; + if (Array.isArray(body)) return classifyBatch(body); + if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { + kind: "legacy", + reason: "response" + }; + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); + return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); +} +/** +* The rejection a modern-only endpoint (no legacy serving configured) +* answers a legacy-classified request with. +* +* - Envelope-less requests (including `initialize`) are answered with the +* unsupported-protocol-version error carrying the endpoint's supported +* versions and echoing the version the request named (when it named one — +* `requested` is omitted rather than fabricated when the request named no +* version at all), so a legacy client can discover what the endpoint serves +* from the error alone. +* - Posted responses and batch arrays are invalid requests on the modern era. +* - Non-`POST` methods are not allowed. +* - Legacy-classified notifications return `undefined`: the caller answers +* 202 with no body and does not dispatch the notification (accept-and-drop). +*/ +function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { + switch (route.reason) { + case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); + case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); + case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); + case "notification": return; + case "initialize": + case "no-claim": { + const requested = route.requestedVersion; + return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: [...supportedVersions], + requested + }), true); + } + } +} + +//#endregion +//#region ../core-internal/src/util/schema.ts +/** +* Internal Zod schema utilities for protocol handling. +* These are used internally by the SDK for protocol message validation. +*/ +/** +* Parses data against a Zod schema (synchronous). +* Returns a discriminated union with success/error. +*/ +function parseSchema(schema, data) { + return parse_safeParse(schema, data); +} +/** +* Union of the declared shape keys across several Zod object schemas. +*/ +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} + +//#endregion +//#region ../core-internal/src/util/standardSchema.ts +/** +* Standard Schema utilities for user-provided schemas. +* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. +* @see https://standardschema.dev +*/ +function isStandardSchema(schema) { + if (schema == null) return false; + const schemaType = typeof schema; + if (schemaType !== "object" && schemaType !== "function") return false; + if (!("~standard" in schema)) return false; + return typeof schema["~standard"]?.validate === "function"; +} +let warnedZodFallback = false; +/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ +const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; +/** +* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. +* +* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt +* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). +* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, +* so for `io: 'input'` this function defaults `type` to `"object"` when absent +* and throws on an explicit non-object `type` (e.g. `z.string()`). For +* `io: 'output'` a non-object root is returned as-is; the `"object"` default is +* applied only when the root is provably object-shaped. +*/ +function standardSchemaToJsonSchema(schema, io = "input") { + const std = schema["~standard"]; + let result; + if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); + else if (std.vendor === "zod") { + if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema()."); + if (!warnedZodFallback) { + warnedZodFallback = true; + console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning."); + } + result = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io + }); + } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); + if (io === "output") { + if (result.type !== void 0) return result; + return isProvablyObjectShapedRoot(result) ? { + type: "object", + ...result + } : result; + } + if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); + return { + type: "object", + ...result + }; +} +/** +* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords +* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a +* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively +* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to +* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. +*/ +function isProvablyObjectShapedRoot(schema) { + if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; + for (const key of [ + "oneOf", + "anyOf", + "allOf" + ]) { + const members = schema[key]; + if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); + } + return false; +} +function formatIssue(issue) { + if (!issue.path?.length) return issue.message; + return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; +} +async function validateStandardSchema(schema, data) { + const result = await schema["~standard"].validate(data); + if (result.issues && result.issues.length > 0) return { + success: false, + error: result.issues.map((i) => formatIssue(i)).join(", ") + }; + return { + success: true, + data: result.value + }; +} +function zodEmittedPattern(schema) { + const jsonSchema = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io: "input" + }); + return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; +} +const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; +function datetimeReferenceSchemas(pattern) { + const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); + const precisions = [ + void 0, + -1, + 0 + ]; + if (fractionDigits) precisions.push(Number(fractionDigits[1])); + return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [schemas_email()]; + break; + case "uri": + referenceSchemas = [schemas_url()]; + break; + case "date": + referenceSchemas = [iso_date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function promptArgumentsFromStandardSchema(schema) { + const jsonSchema = standardSchemaToJsonSchema(schema, "input"); + const properties = jsonSchema.properties || {}; + const required = jsonSchema.required || []; + return Object.entries(properties).map(([name, prop]) => ({ + name, + description: prop?.description, + required: required.includes(name) + })); +} + +//#endregion +//#region ../core-internal/src/shared/elicitation.ts +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); +const PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) +}; +const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); +/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ +function walkProperty(node, path, vendor, unsupported) { + if (!isJsonObject(node)) return node; + const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; + if (allowedKeys === void 0) return node; + const pruned = {}; + for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; + else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { + if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; + else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); + } else unsupported.push(`${path}.${key}`); + return pruned; +} +/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ +function walkRequestedSchema(converted, vendor) { + const pruned = {}; + const unsupported = []; + for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); + else if (ROOT_KEYS.has(key)) pruned[key] = value; + else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); + if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ +function describeUnsupportedProperties(pruned, fallback) { + if (!isJsonObject(pruned.properties)) return fallback; + const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); + return offenders.length > 0 ? offenders.join(", ") : fallback; +} +function findDroppedConstraintPaths(original, parsed, path = "") { + if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); + if (!isJsonObject(original) || !isJsonObject(parsed)) return []; + return Object.entries(original).flatMap(([key, value]) => { + const childPath = path ? `${path}.${key}` : key; + if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; + return findDroppedConstraintPaths(value, parsed[key], childPath); + }); +} +/** Converts an authoring-friendly elicitation input into its wire-ready form. */ +function normalizeElicitInputParams(input) { + if (!isStandardSchema(input.requestedSchema)) return { + ...input, + mode: "form", + requestedSchema: input.requestedSchema + }; + const vendor = input.requestedSchema["~standard"].vendor; + const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); + const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); + const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); + if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); + const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); + if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequired.ts +/** +* Authoring helpers for multi-round-trip requests (protocol revision +* 2026-07-28). +* +* A handler for one of the multi-round-trip methods (`tools/call`, +* `prompts/get`, `resources/read`) requests additional client input by +* returning an {@linkcode InputRequiredResult} instead of a final result. The +* helpers here build that return value and its embedded requests as NEUTRAL +* values; only the 2026-07-28 wire codec maps them to/from the wire. The +* 2025-era codec has no input-required vocabulary — on a 2025-era request the +* server's legacy shim (on by default) fulfils the embedded requests as real +* server→client requests and re-enters the handler, so the same return shape +* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores +* the pre-shim loud failure. +* +* There is no nominal brand: `resultType: 'input_required'` is the +* discriminator, and hand-built result literals are equally legal — the +* server seam re-checks the at-least-one rule for them. +*/ +function buildInputRequired(spec) { + const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; + const hasRequestState = typeof spec.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)"); + return { + resultType: "input_required", + ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, + ...spec.requestState !== void 0 && { requestState: spec.requestState } + }; +} +/** +* Builder for the input-required return value of multi-round-trip handlers, +* with per-kind constructors for the embedded requests +* (`inputRequired.elicit`, `inputRequired.elicitUrl`, +* `inputRequired.createMessage`, `inputRequired.listRoots`). +* +* @example Write-once tool requesting confirmation +* ```ts +* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { +* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); +* if (!confirmed) { +* return inputRequired({ +* inputRequests: { +* confirm: inputRequired.elicit({ +* message: `Deploy to ${env}?`, +* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } +* }) +* } +* }); +* } +* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; +* }); +* ``` +*/ +const inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error) { + throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } +}); +function acceptedContent(responses, key, schema) { + const view = inputResponse(responses, key); + if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; + if (schema === void 0) return view.content; + const outcome = schema["~standard"].validate(view.content); + if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); + return outcome.issues === void 0 ? outcome.value : void 0; +} +/** +* Reads one entry of a retried request's `inputResponses` +* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering +* decline/cancel detection and the non-elicitation response kinds that +* {@linkcode acceptedContent} does not surface. +* +* The values arrive from the client and are not re-validated here — treat +* them as untrusted input (validate elicitation content with the +* schema-aware {@linkcode acceptedContent} overload where it matters). +*/ +function inputResponse(responses, key) { + if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; + const entry = responses[key]; + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; + const candidate = entry; + if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { + const content = candidate["content"]; + return { + kind: "elicit", + action: candidate["action"], + ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } + }; + } + if (Array.isArray(candidate["roots"])) return { + kind: "roots", + roots: candidate["roots"] + }; + if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { + kind: "sampling", + result: candidate + }; + return { kind: "missing" }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredDriver.ts +/** +* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). +* +* When a request to one of the multi-round-trip methods comes back as +* `input_required`, the driver fulfils the embedded input requests by +* dispatching them to the client's already-registered handlers (elicitation, +* sampling, roots — one generic engine, no per-feature API), then retries the +* original request with the collected `inputResponses` and a byte-exact echo +* of `requestState`, on a fresh request id, until the server returns a +* complete result or the round cap is exhausted. +* +* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the +* same primitive a manual caller uses (`allowInputRequired` semantics — the +* retry hands back the next `input_required` payload instead of recursing), +* so the loop, the cap, and the pacing live in one place and disabling +* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this +* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to +* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by +* shrinking the budget passed to each leg — no new timer system. +*/ +/** +* Fixed pacing applied before retrying a requestState-only (load-shedding) +* leg — a leg that carries no embedded input requests, so nothing slows the +* loop down naturally. Counted in the same round cap. +*/ +const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; +/** +* The message both multi-round-trip loops emit when the round cap is +* exhausted — the client driver as a typed error, the server-side legacy +* shim as its per-family failure. One formatter so the texts cannot drift +* (hosts and models read the tool-result copy verbatim). +*/ +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +/** +* Abortable delay: resolves after `ms`, or rejects with the signal's reason +* (wrapped in an `SdkError` when it isn't already one) if the signal aborts +* first. Aborting after resolution is a no-op. Shared with the server-side +* legacy shim (the pacing semantics must match per era). +*/ +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +/** +* A per-round abort linked to the caller's signal: the embedded sibling +* dispatches share it, so the first failure (or a caller abort) cancels the +* others instead of leaving them running. Shared with the server-side legacy +* shim (the abort-linkage semantics must match per era). +*/ +function linkedRoundAbort(outer) { + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(outer?.reason); + outer?.addEventListener("abort", onOuterAbort, { once: true }); + if (outer?.aborted) controller.abort(outer.reason); + return { + signal: controller.signal, + abort: (reason) => controller.abort(reason), + dispose: () => outer?.removeEventListener("abort", onOuterAbort) + }; +} + +//#endregion +//#region ../core-internal/src/types/specTypeSchema.ts +/** +* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. +* +* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no +* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, +* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). +* Keeping the list explicit means new public spec types must be added here deliberately, and +* internals never leak into `SpecTypeName`. +* +* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` +* (the bare name collides with the server package's `ResourceTemplate` class), so +* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to +* a type literally named `ResourceTemplate`. +*/ +const SPEC_SCHEMA_KEYS = [ + "AnnotationsSchema", + "AudioContentSchema", + "BaseMetadataSchema", + "BlobResourceContentsSchema", + "BooleanSchemaSchema", + "CallToolRequestSchema", + "CallToolRequestParamsSchema", + "CallToolResultSchema", + "CancelledNotificationSchema", + "CancelledNotificationParamsSchema", + "CancelTaskRequestSchema", + "CancelTaskResultSchema", + "ClientCapabilitiesSchema", + "ClientNotificationSchema", + "ClientRequestSchema", + "ClientResultSchema", + "CompatibilityCallToolResultSchema", + "CompleteRequestSchema", + "CompleteRequestParamsSchema", + "CompleteResultSchema", + "ContentBlockSchema", + "CreateMessageRequestSchema", + "CreateMessageRequestParamsSchema", + "CreateMessageResultSchema", + "CreateMessageResultWithToolsSchema", + "CreateTaskResultSchema", + "CursorSchema", + "DiscoverRequestSchema", + "DiscoverResultSchema", + "ElicitationCompleteNotificationSchema", + "ElicitationCompleteNotificationParamsSchema", + "ElicitRequestSchema", + "ElicitRequestFormParamsSchema", + "ElicitRequestParamsSchema", + "ElicitRequestURLParamsSchema", + "ElicitResultSchema", + "EmbeddedResourceSchema", + "EmptyResultSchema", + "EnumSchemaSchema", + "GetPromptRequestSchema", + "GetPromptRequestParamsSchema", + "GetPromptResultSchema", + "GetTaskPayloadRequestSchema", + "GetTaskPayloadResultSchema", + "GetTaskRequestSchema", + "GetTaskResultSchema", + "IconSchema", + "IconsSchema", + "ImageContentSchema", + "ImplementationSchema", + "InitializedNotificationSchema", + "InitializeRequestSchema", + "InitializeRequestParamsSchema", + "InitializeResultSchema", + "JSONArraySchema", + "JSONObjectSchema", + "JSONRPCErrorResponseSchema", + "JSONRPCMessageSchema", + "JSONRPCNotificationSchema", + "JSONRPCRequestSchema", + "JSONRPCResponseSchema", + "JSONRPCResultResponseSchema", + "JSONValueSchema", + "LegacyTitledEnumSchemaSchema", + "ListPromptsRequestSchema", + "ListPromptsResultSchema", + "ListResourcesRequestSchema", + "ListResourcesResultSchema", + "ListResourceTemplatesRequestSchema", + "ListResourceTemplatesResultSchema", + "ListRootsRequestSchema", + "ListRootsResultSchema", + "ListTasksRequestSchema", + "ListTasksResultSchema", + "ListToolsRequestSchema", + "ListToolsResultSchema", + "LoggingLevelSchema", + "LoggingMessageNotificationSchema", + "LoggingMessageNotificationParamsSchema", + "ModelHintSchema", + "ModelPreferencesSchema", + "MultiSelectEnumSchemaSchema", + "NotificationSchema", + "NumberSchemaSchema", + "PaginatedRequestSchema", + "PaginatedRequestParamsSchema", + "PaginatedResultSchema", + "PingRequestSchema", + "PrimitiveSchemaDefinitionSchema", + "ProgressSchema", + "ProgressNotificationSchema", + "ProgressNotificationParamsSchema", + "ProgressTokenSchema", + "PromptSchema", + "PromptArgumentSchema", + "PromptListChangedNotificationSchema", + "PromptMessageSchema", + "PromptReferenceSchema", + "ReadResourceRequestSchema", + "ReadResourceRequestParamsSchema", + "ReadResourceResultSchema", + "RelatedTaskMetadataSchema", + "RequestSchema", + "RequestIdSchema", + "RequestMetaSchema", + "ResourceSchema", + "ResourceContentsSchema", + "ResourceLinkSchema", + "ResourceListChangedNotificationSchema", + "ResourceRequestParamsSchema", + "ResourceTemplateSchema", + "ResourceTemplateReferenceSchema", + "ResourceUpdatedNotificationSchema", + "ResourceUpdatedNotificationParamsSchema", + "ResultMetaObjectSchema", + "ResultSchema", + "RoleSchema", + "RootSchema", + "RootsListChangedNotificationSchema", + "SamplingContentSchema", + "SamplingMessageSchema", + "SamplingMessageContentBlockSchema", + "ServerCapabilitiesSchema", + "ServerNotificationSchema", + "ServerRequestSchema", + "ServerResultSchema", + "SetLevelRequestSchema", + "SetLevelRequestParamsSchema", + "SingleSelectEnumSchemaSchema", + "StringSchemaSchema", + "SubscribeRequestSchema", + "SubscribeRequestParamsSchema", + "SubscriptionFilterSchema", + "SubscriptionsAcknowledgedNotificationSchema", + "SubscriptionsAcknowledgedNotificationParamsSchema", + "SubscriptionsListenRequestSchema", + "SubscriptionsListenRequestParamsSchema", + "SubscriptionsListenResultSchema", + "SubscriptionsListenResultMetaSchema", + "TaskAugmentedRequestParamsSchema", + "TaskCreationParamsSchema", + "TaskMetadataSchema", + "TaskSchema", + "TaskStatusSchema", + "TaskStatusNotificationSchema", + "TaskStatusNotificationParamsSchema", + "TextContentSchema", + "TextResourceContentsSchema", + "TitledMultiSelectEnumSchemaSchema", + "TitledSingleSelectEnumSchemaSchema", + "ToolSchema", + "ToolAnnotationsSchema", + "ToolChoiceSchema", + "ToolExecutionSchema", + "ToolListChangedNotificationSchema", + "ToolResultContentSchema", + "ToolUseContentSchema", + "UnsubscribeRequestSchema", + "UnsubscribeRequestParamsSchema", + "UntitledMultiSelectEnumSchemaSchema", + "UntitledSingleSelectEnumSchemaSchema" +]; +const authSchemas = { + IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, + OAuthClientInformationSchema: OAuthClientInformationSchema, + OAuthClientMetadataSchema: OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema: OAuthErrorResponseSchema, + OAuthMetadataSchema: OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, + OAuthTokensSchema: OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema +}; +const _specTypeSchemas = {}; +const _isSpecType = {}; +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); +for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); +/** +* Runtime validators for every MCP spec type, keyed by type name. +* +* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for +* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from +* storage that should be a `Tool`. +* +* Each entry implements the Standard Schema interface, so it composes with any +* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" +* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); +* if (result.issues === undefined) { +* // result.value is CallToolResult +* } +* ``` +*/ +const specTypeSchemas = Object.freeze(_specTypeSchemas); +/** +* Type predicates for every MCP spec type, keyed by type name. +* +* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and +* transforms are applied), and narrows to that input type. For schemas with `.default()` or +* `.preprocess()`, this may accept values that do not structurally match the named output type; +* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use +* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. +* +* Each guard is a standalone function, so it can be passed directly as a callback. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" +* if (isSpecType.ContentBlock(value)) { +* // value is ContentBlock +* } +* +* const blocks = mixed.filter(isSpecType.ContentBlock); +* ``` +*/ +const isSpecType = Object.freeze(_isSpecType); + +//#endregion +//#region ../core-internal/src/wire/bootstrap.ts +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); + case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); + default: return; + } +} + +//#endregion +//#region ../core-internal/src/shared/protocol.ts +/** +* The default request timeout, in milliseconds. +*/ +const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +/** +* The reserved per-request `_meta` envelope keys (protocol revision +* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before +* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are +* wire-level bookkeeping, not handler material. +*/ +const RESERVED_ENVELOPE_META_KEYS = [ + auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, + auth_CUe6YdwF_CLIENT_INFO_META_KEY, + auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY +]; +/** +* Top-level params members carrying multi-round-trip driver material +* (protocol revision 2026-07-28). The spec reserves these names on +* client-initiated REQUESTS only — notification params keep them untouched +* (a vendor notification may legitimately use the same names). +*/ +const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; +/** +* Lift wire-only material out of an inbound message so handlers see exactly +* the 2025-era shape, and surface it for the protocol layer (requests: via +* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the +* reserved envelope `_meta` keys are reserved on every message, while the +* multi-round-trip retry fields (`inputResponses`/`requestState`) are +* reserved on client-initiated requests only — so notifications get only the +* envelope lift, and their top-level params stay untouched. Messages without +* wire-only material are returned unchanged (same reference). +*/ +function liftWireOnlyMaterial(message, kind) { + const params = message.params; + if (!isPlainObject$1(params)) return { + message, + lifted: {} + }; + const meta = params._meta; + const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { + const envelope = {}; + const nextMeta = { ...meta }; + for (const key of envelopeKeys) { + envelope[key] = meta[key]; + delete nextMeta[key]; + } + lifted.envelope = envelope; + if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; + else delete nextParams._meta; + } + for (const key of retryKeys) { + if (key === "inputResponses") lifted.inputResponses = nextParams[key]; + if (key === "requestState") lifted.requestState = nextParams[key]; + delete nextParams[key]; + } + return { + message: { + ...message, + params: nextParams + }, + lifted + }; +} +/** +* Standard Schema adapter over the era codec's `validateResult` function (the +* function-only WireCodec contract exposes no schema objects). Used by the +* spec-method `request()` overload so the request funnel keeps a single +* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema +* paths. +* +* Returns `undefined` when the method has no result entry on this era's +* registry — the caller maps that to the synchronous "pass a result schema" +* TypeError, exactly matching the pre-function-only behavior the +* typedMapAlignment suite pins (the result map deliberately excludes the +* `tasks/*` methods, so the spec-method overload refuses them up front). +*/ +function codecResultValidator(codec, method) { + const probe = codec.validateResult(method, void 0); + if (!probe.ok && probe.reason === "not-in-era") return void 0; + return { "~standard": { + version: 1, + vendor: "mcp-wire-codec", + validate(value) { + const outcome = codec.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +/** +* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The +* `as T` below is the one place {@linkcode RequestStateAccessor}'s +* caller-asserted typing is implemented — no implementation can produce an +* arbitrary `T` from a runtime value honestly. +*/ +function requestStateAccessor(value) { + return () => value; +} +/** Shared no-state accessor: the common case allocates nothing per request. */ +const NO_REQUEST_STATE = requestStateAccessor(void 0); +/** +* Returns a context whose `requestState` accessor reads the given value — +* how the server seam hands a verify hook's decoded payload (or the legacy +* shim's per-round echo) to the handler without mutating the original +* context. +*/ +function withRequestStateValue(ctx, value) { + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + requestState: requestStateAccessor(value) + } + }; +} +let writeNegotiatedProtocolVersion; +/** +* Package-internal write channel for a {@linkcode Protocol} instance's +* negotiated protocol version, for callers outside the class hierarchy: +* tests and the (future) modern-era server entry that marks a factory +* instance modern at binding time. Exported on the core internal barrel +* only — never public API. +*/ +function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { + writeNegotiatedProtocolVersion(instance, version); +} +/** +* Implements MCP protocol framing on top of a pluggable transport, including +* features like request/response linking, notifications, and progress. +* +* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific +* implementations most code should use. +*/ +var Protocol = class { + _transport; + _requestMessageId = 0; + _requestHandlers = /* @__PURE__ */ new Map(); + _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + _notificationHandlers = /* @__PURE__ */ new Map(); + _responseHandlers = /* @__PURE__ */ new Map(); + _progressHandlers = /* @__PURE__ */ new Map(); + _timeoutInfo = /* @__PURE__ */ new Map(); + _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + /** + * The protocol version negotiated for the current connection (`undefined` + * before negotiation completes), which determines the wire era this + * instance speaks. Set by the SDK's negotiation and initialize paths + * (`Client.connect`, `Server._oninitialize`). + */ + _negotiatedProtocolVersion; + static { + writeNegotiatedProtocolVersion = (instance, version) => { + instance._negotiatedProtocolVersion = version; + }; + } + _supportedProtocolVersions; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when {@linkcode Protocol.close | close()} is called as well. + */ + onclose; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler; + constructor(_options) { + this._options = _options; + this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; + this.setNotificationHandler("notifications/cancelled", (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler("notifications/progress", (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler("ping", (_request) => ({})); + } + /** + * Drop consult for inbound messages whose transport did not classify them + * at the edge — long-lived channels such as stdio, where a role class may + * need to decline traffic the negotiated era has no answer for (the + * client-side inbound-request drop on modern-era connections: the + * 2026-07-28 era has no server→client request channel, and on stdio the + * client must never write JSON-RPC responses). + * + * Consulted ONLY when the transport supplied no + * {@linkcode MessageExtraInfo.classification}: edge-classified traffic + * never reaches the hook. Returning `'drop'` discards the message without + * writing any response (requests are surfaced via `onerror`). The base + * implementation returns `undefined`: unclassified traffic keeps today's + * dispatch path unchanged. Era selection never happens here — era is + * instance state, owned by the serving entry that constructed and + * connected the instance. + */ + _shouldDropInbound(_message) {} + /** + * The per-request `_meta` envelope this instance attaches to every outgoing + * request and notification, when one applies. The base implementation + * returns `undefined` (no envelope — the 2025-era posture, so legacy-era + * outbound traffic is byte-identical to a build without this seam). + * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) + * era to return the reserved protocol-version / client-info / + * client-capabilities keys. User-supplied `_meta` keys take precedence over + * the auto-attached ones. + */ + _outboundMetaEnvelope() {} + /** + * Attach this instance's outbound `_meta` envelope (when one is configured) + * to a request or notification. A no-op when the seam returns `undefined` + * — the message returns by reference, so the legacy-era wire stays + * byte-identical. User-supplied `_meta` keys are spread last so they win + * over the auto-attached envelope keys. + */ + _envelopeOutbound(message) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message; + const params = message.params ?? {}; + return { + ...message, + params: { + ...params, + _meta: { + ...envelope, + ...params._meta + } + } + }; + } + /** + * Extension point for non-`complete` decoded results in the response + * funnel: a result the wire codec discriminated into a kind other than + * `'complete'` or `'invalid'` is handed here for the role class to + * resolve. The base default surfaces it as a typed + * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). + * + * Intended consumers (named so the seam stays accountable): + * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils + * `'input_required'` results through the registered + * elicitation/sampling/roots handlers and retries via `flow.retry`; + * - a future client-side terminal-result handler for + * `subscriptions/listen`, when the spec defines one. + * + * `Server` instances never receive `input_required` responses on their + * outbound legs and leave the base behavior in place. + */ + _resolveNonCompleteResult(decoded, flow) { + return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { + resultType: decoded.kind, + method: flow.request.method + })); + } + /** + * Protected accessor for a registered request handler. Used by role + * classes that dispatch synthesized requests through the same stored + * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip + * input request). + */ + _getRequestHandler(method) { + return this._requestHandlers.get(method); + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + try { + _onclose?.(); + } finally { + this._onclose(); + } + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); + await this._transport.start(); + } + /** + * Transport-close hook. Subclass overrides MUST call `super._onclose()` + * after their own cleanup — base teardown (response-handler settlement, + * timeout clearing, in-flight request abort) does not run otherwise. + */ + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + const requestHandlerAbortControllers = this._requestHandlerAbortControllers; + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + /** + * Inbound-notification dispatch. Subclass overrides MUST delegate + * unmatched traffic to `super._onnotification(rawNotification, extra)` — + * an override that consumes only what it owns and falls through to base + * dispatch for everything else. + */ + _onnotification(rawNotification, extra) { + const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; + const handler = this._notificationHandlers.get(notification.method); + const fallback = this.fallbackNotificationHandler; + if (handler === void 0 && fallback === void 0) return; + Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { + this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); + return; + } + const capturedTransport = this._transport; + const sendErrorResponse = (code, message, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); + return; + } + const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { + ...options, + relatedRequestId: request.id + }); + const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { + ...options, + relatedRequestId: request.id + }); + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); + const baseCtx = { + sessionId: capturedTransport?.sessionId, + mcpReq: { + id: request.id, + method: request.method, + _meta: request.params?._meta, + ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, + ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, + ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, + requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), + signal: abortController.signal, + send: ((r, schemaOrOptions, maybeOptions) => { + const sendCodec = this._resolveOutboundCodec(r.method); + this._assertOutboundRequestInEra(sendCodec, r.method); + if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(sendCodec, r.method); + if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); + return sendRequest(r, validate, schemaOrOptions); + }), + notify: sendNotification + }, + http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 + }; + const ctx = this.buildContext(baseCtx, extra); + Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { + if (abortController.signal.aborted) return; + let encoded; + try { + encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec.encodeErrorCode(thrownCode), + message: error.message ?? "Internal error", + ...error["data"] !== void 0 && { data: error["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + handler(params); + } + /** + * Inbound-response dispatch. Subclass overrides MUST delegate unmatched + * traffic to `super._onresponse(response)` — an override that consumes + * only what it owns and falls through to base dispatch for everything + * else. + */ + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._progressHandlers.delete(messageId); + if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); + else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + request(request, schemaOrOptions, maybeOptions) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec, request.method); + if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); + return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); + } + /** + * The wire codec for this instance's negotiated era — the phase-2 truth: + * everything an established connection sends and receives resolves + * through it. Legacy until a version has been negotiated. + */ + _negotiatedWireCodec() { + return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + } + /** + * Protected accessor for the instance's negotiated wire codec, for role + * classes (Client/Server/McpServer) routing era-dependent behavior + * through the codec's function-only surface — `samplingResultVariant`, + * `outboundEnvelope`, `projectCallToolResult` — instead of branching on + * the protocol version themselves. + */ + _wireCodec() { + return this._negotiatedWireCodec(); + } + /** + * Outbound codec resolution: while the negotiated version is still unset + * (the negotiation window), lifecycle messages are bootstrap-pinned BY + * METHOD — they self-identify their era (`initialize` IS the legacy + * handshake, `server/discover` IS the modern probe). Once a version has + * been negotiated, the instance era is authoritative for everything — a + * negotiated session never re-routes a method onto the other era. + */ + _resolveOutboundCodec(method) { + if (this._negotiatedProtocolVersion === void 0) { + const pinned = bootstrapOutboundCodec(method); + if (pinned) return pinned; + } + return this._negotiatedWireCodec(); + } + /** + * Era gate for outbound requests — deletions are physical in BOTH + * directions: sending a spec method that the resolved era does not define + * dies locally with a typed error before anything reaches the transport. + * Methods outside the spec universe are consumer-owned extension methods + * and stay era-blind. + */ + _assertOutboundRequestInEra(codec, method) { + if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method, + era: codec.era + }); + } + /** + * Sends a request and waits for a response, using the provided schema for + * validation instead of the era registry's method-keyed entry. + * + * This is the internal implementation used by SDK methods whose result + * schema cannot be expressed as a method-keyed registry entry — the one + * surviving case is `server.createMessage`, whose result schema depends + * on the REQUEST params (tools vs no tools) — and by callers passing + * explicit compatibility schemas. Spec methods are still era-gated here: + * an explicit schema never smuggles a deleted method onto the wire. + */ + _requestWithSchema(request, resultSchema, options) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); + } + /** + * The request funnel proper, keyed by the resolved era codec: the codec + * owns result decoding (raw-first `resultType` discrimination — V-1 — + * and the era's lift posture) before the schema validation step. + */ + _requestWithSchemaViaCodec(codec, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error) { + earlyReject(error); + return; + } + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; + const messageId = this._requestMessageId++; + cleanupMessageId = messageId; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta, + progressToken: messageId + } + }; + } + const outbound = this._envelopeOutbound(jsonrpcRequest); + let responseReceived = false; + const cancel = (reason) => { + if (responseReceived) return; + this._progressHandlers.delete(messageId); + if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }), { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); + else requestAbort.abort(); + reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + responseReceived = true; + if (response instanceof Error) return reject(response); + let decoded; + try { + decoded = codec.decodeResult(request.method, response.result); + } catch (error) { + return reject(error instanceof Error ? error : new Error(String(error))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { + method: request.method, + params + }, resultSchema, legOptions) + }; + return resolve(this._resolveNonCompleteResult(decoded, flow)); + } + const result = decoded.result; + validateStandardSchema(resultSchema, result).then((parseResult) => { + if (parseResult.success) resolve(parseResult.data); + else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); + }, reject); + }); + onAbort = () => cancel(options?.signal?.reason); + options?.signal?.addEventListener("abort", onAbort, { once: true }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + this._transport.send(outbound, { + relatedRequestId, + resumptionToken, + onresumptiontoken, + headers, + requestSignal: requestAbort?.signal + }).catch((error) => { + this._progressHandlers.delete(messageId); + reject(error); + }); + }).finally(() => { + if (onAbort) options?.signal?.removeEventListener("abort", onAbort); + if (cleanupMessageId !== void 0) { + this._responseHandlers.delete(cleanupMessageId); + this._cleanupTimeout(cleanupMessageId); + } + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); + } + /** + * The notification funnel proper, keyed by the resolved era codec — + * direct sends and related notifications (`ctx.mcpReq.notify`) alike + * resolve through the instance's negotiated era at send time. + */ + async _notificationViaCodec(codec, notification, options) { + if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method: notification.method, + era: codec.era + }); + this.assertNotificationCapability(notification.method); + const jsonrpcNotification = this._envelopeOutbound({ + jsonrpc: "2.0", + ...notification + }); + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); + }); + return; + } + await this._transport.send(jsonrpcNotification, options); + } + setRequestHandler(method, schemasOrHandler, maybeHandler) { + this.assertRequestHandlerCapability(method); + let stored; + if (typeof schemasOrHandler === "function") { + if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); + stored = (request, ctx) => { + const dispatchCodec = this._negotiatedWireCodec(); + let outcome = dispatchCodec.validateRequest(method, request); + if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value, ctx)); + }; + } else if (maybeHandler) stored = async (request, ctx) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); + return maybeHandler(parsed.data, ctx); + }; + else throw new TypeError("setRequestHandler: handler is required"); + this._requestHandlers.set(method, this._wrapHandler(method, stored)); + } + /** + * Hook for subclasses to wrap a registered request handler with role-specific + * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` + * validates `elicitation/create` mode and result). Runs for both the 2-arg and + * 3-arg registration paths. The default implementation is identity. + * + * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. + */ + _wrapHandler(_method, handler) { + return handler; + } + /** + * Hook for subclasses to supply the implementation identity the 2026-era + * encode seam stamps into outbound result `_meta` under + * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD + * identify themselves on every response). The default is `undefined` — no + * stamp. Only `Server` overrides this: the key identifies the software + * producing a response, and the 2025-era codec never stamps anything + * regardless (the never-stamp guarantee). + */ + _outboundServerInfo() {} + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + setNotificationHandler(method, schemasOrHandler, maybeHandler) { + if (typeof schemasOrHandler === "function") { + if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); + this._notificationHandlers.set(method, (notification, codec) => { + const outcome = codec.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value)); + }); + return; + } + if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); + this._notificationHandlers.set(method, async (notification) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); + await maybeHandler(parsed.data, notification); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +}; +function isPlainObject$1(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { + ...baseValue, + ...addValue + } : addValue; + } + return result; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredEngine.ts +function src_CX2iR2pK_isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** +* Splits a retried request's `inputResponses` map into the BARE response +* entries the spec defines and everything else. The spec's embedded responses +* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or +* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some +* peers emit) is never accepted as a response — its key is recorded so the +* handler can re-issue the corresponding input request. +*/ +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +/** +* Builds the manual-mode {@linkcode InputRequiredResult} value from the +* codec's decoded payload — what an `allowInputRequired: true` caller +* receives instead of the auto-fulfilled complete result. +*/ +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} + +//#endregion +//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js +/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/ +var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + /** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + /** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse; + /** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + function parse(string) { + if (!string) throw new TypeError("argument string is required"); + var header = typeof string === "object" ? getcontenttype(string) : string; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + /** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + /** + * Class to represent a content type. + * @private + */ + function ContentType(type) { + this.parameters = Object.create(null); + this.type = type; + } +})); + +//#endregion +//#region ../core-internal/src/shared/mediaType.ts +var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); +/** +* Extracts the media type (the lowercased `type/subtype` pair, without +* parameters) from a raw `Content-Type` header value, or `undefined` when the +* header is missing or empty. +* +* Content-Type comparisons must use the parsed media type, never a substring +* search of the raw header: a value like `text/plain; a=application/json` +* contains the substring `application/json` but its media type is +* `text/plain`, and case variants or parameters make naive string comparison +* wrong in both directions. +* +* "Essence" is the WHATWG MIME Sniffing standard's term for the bare +* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); +* the Fetch standard's request classification is defined against it +* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). +* +* Parsing is RFC 9110 (`content-type` package) first. When the parameter +* section is malformed (`application/json;`, `application/json; charset=`), +* browsers and most HTTP stacks still derive the media type from the segment +* before the first `;` — the fallback matches that widely-implemented +* behavior, so a header whose media type is unambiguous is not rejected for +* a sloppy parameter section. +*/ +function src_CX2iR2pK_mediaTypeEssence(header) { + if (!header) return; + try { + return import_content_type.parse(header).type; + } catch { + const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); + if (essence === "" || header.slice(essence.length).includes(",")) return; + return essence; + } +} +/** +* Whether a raw `Content-Type` header value denotes `application/json`. +* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed +* parameter sections do not reject a header whose media type is unambiguously +* `application/json` (see `mediaTypeEssence` for the exact grammar). +*/ +function src_CX2iR2pK_isJsonContentType(header) { + if (header === "application/json") return true; + return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; +} + +//#endregion +//#region ../core-internal/src/shared/metadataUtils.ts +/** +* Utilities for working with {@linkcode BaseMetadata} objects. +*/ +/** +* Gets the display name for an object with {@linkcode BaseMetadata}. +* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` +* For other objects: `title` → `name` +* This implements the spec requirement: "if no title is provided, name should be used for display purposes" +*/ +function getDisplayName(metadata) { + if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; + if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; + return metadata.name; +} + +//#endregion +//#region ../core-internal/src/shared/stdio.ts +const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; +/** +* Buffers a continuous stdio stream into discrete JSON-RPC messages. +*/ +var ReadBuffer = class { + _buffer; + _maxBufferSize; + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; + } + append(chunk) { + if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + while (this._buffer) { + const index = this._buffer.indexOf("\n"); + if (index === -1) return null; + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + try { + return deserializeMessage(line); + } catch (error) { + if (error instanceof SyntaxError) continue; + throw error; + } + } + return null; + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +//#endregion +//#region ../core-internal/src/shared/toolNameValidation.ts +/** +* Tool name validation utilities according to SEP: Specify Format for Tool Names +* +* Tool names SHOULD be between 1 and 128 characters in length (inclusive). +* Tool names are case-sensitive. +* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits +* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). +* Tool names SHOULD NOT contain spaces, commas, or other special characters. +* +* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} +*/ +/** +* Regular expression for valid tool names according to SEP-986 specification +*/ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** +* Validates a tool name according to the SEP specification +* @param name - The tool name to validate +* @returns An object containing validation result and any warnings +*/ +function validateToolName(name) { + const warnings = []; + if (name.length === 0) return { + isValid: false, + warnings: ["Tool name cannot be empty"] + }; + if (name.length > 128) return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); + if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); + if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); + warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** +* Issues warnings for non-conforming tool names +* @param name - The tool name that triggered the warnings +* @param warnings - Array of warning messages +*/ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) console.warn(` - ${warning}`); + console.warn("Tool registration will proceed, but this may cause compatibility issues."); + console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); + console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); + } +} +/** +* Validates a tool name and issues warnings for non-conforming names +* @param name - The tool name to validate +* @returns `true` if the name is valid, `false` otherwise +*/ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + issueToolNameWarning(name, result.warnings); + return result.isValid; +} + +//#endregion +//#region ../core-internal/src/shared/transport.ts +/** +* Normalizes `HeadersInit` to a plain `Record` for manipulation. +* Handles `Headers` objects, arrays of tuples, and plain objects. +*/ +function normalizeHeaders(headers) { + if (!headers) return {}; + if (headers instanceof Headers) return Object.fromEntries(headers.entries()); + if (Array.isArray(headers)) return Object.fromEntries(headers); + return { ...headers }; +} +/** +* Creates a fetch function that includes base `RequestInit` options. +* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. +* +* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) +* @param baseInit - The base `RequestInit` to merge with each request +* @returns A wrapped fetch function that merges base options with call-specific options +*/ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url, init) => { + return baseFetch(url, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} + +//#endregion +//#region ../core-internal/src/shared/uriTemplate.ts +const MAX_TEMPLATE_LENGTH = 1e6; +const MAX_VARIABLE_LENGTH = 1e6; +const MAX_TEMPLATE_EXPRESSIONS = 1e4; +const MAX_REGEX_LENGTH = 1e6; +var src_CX2iR2pK_UriTemplate = class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like `{foo}` or `{?bar}`. + */ + static isTemplate(str) { + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + template; + parts; + get variableNames() { + return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ""; + let i = 0; + let expressionCount = 0; + while (i < template.length) if (template[i] === "{") { + if (currentText) { + parts.push(currentText); + currentText = ""; + } + const end = template.indexOf("}", i); + if (end === -1) throw new Error("Unclosed template expression"); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes("*"); + const names = this.getNames(expr); + const name = names[0]; + for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + parts.push({ + name, + operator, + names, + exploded + }); + i = end + 1; + } else { + currentText += template[i]; + i++; + } + if (currentText) parts.push(currentText); + return parts; + } + getOperator(expr) { + return [ + "+", + "#", + ".", + "/", + "?", + "&" + ].find((op) => expr.startsWith(op)) || ""; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); + if (operator === "+" || operator === "#") return encodeURI(value); + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === "?" || part.operator === "&") { + const pairs = part.names.map((name) => { + const value$1 = variables[name]; + if (value$1 === void 0) return ""; + return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; + }).filter((pair) => pair.length > 0); + if (pairs.length === 0) return ""; + return (part.operator === "?" ? "?" : "&") + pairs.join("&"); + } + if (part.names.length > 1) { + const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); + if (values.length === 0) return ""; + return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); + } + const value = variables[part.name]; + if (value === void 0) return ""; + const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); + switch (part.operator) { + case "": return encoded.join(","); + case "+": return encoded.join(","); + case "#": return "#" + encoded.join(","); + case ".": return "." + encoded.join("."); + case "/": return "/" + encoded.join("/"); + default: return encoded.join(","); + } + } + expand(variables) { + let result = ""; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === "string") { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) continue; + result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; + if (part.operator === "?" || part.operator === "&") hasQueryParam = true; + } + return result; + } + escapeRegExp(str) { + return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); + } + partToRegExp(part) { + const patterns = []; + for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + if (part.operator === "?" || part.operator === "&") { + for (let i = 0; i < part.names.length; i++) { + const name$1 = part.names[i]; + const prefix = i === 0 ? "\\" + part.operator : "&"; + patterns.push({ + pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", + name: name$1 + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case "": + pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; + break; + case "+": + case "#": + pattern = "(.+)"; + break; + case ".": + pattern = String.raw`\.([^/,]+)`; + break; + case "/": + pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); + break; + default: pattern = "([^/]+)"; + } + patterns.push({ + pattern, + name + }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); + let pattern = "^"; + const names = []; + for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ + name, + exploded: part.exploded + }); + } + } + pattern += "$"; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) return null; + const result = {}; + for (const [i, name_] of names.entries()) { + const { name, exploded } = name_; + const value = match[i + 1]; + const cleanName = name.replace("*", ""); + result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; + } + return result; + } +}; + +//#endregion +//#region ../core-internal/src/util/inMemory.ts +/** +* In-memory transport for creating clients and servers that talk to each other within the same process. +* +* Intended for testing and development. For production in-process connections, use +* `StreamableHTTPClientTransport` against a local server URL. +*/ +var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { + _otherTransport; + _messageQueue = []; + _closed = false; + onclose; + onerror; + onmessage; + sessionId; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + if (this._closed) return; + this._closed = true; + const other = this._otherTransport; + this._otherTransport = void 0; + try { + await other?.close(); + } finally { + this.onclose?.(); + } + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + else this._otherTransport._messageQueue.push({ + message, + extra: { authInfo: options?.authInfo } + }); + } +}; + +//#endregion +//#region ../core-internal/src/util/zodCompat.ts +/** +* Zod-specific helpers for the v1-compat raw-shape shorthand on +* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so +* that file stays library-agnostic per the Standard Schema spec. +*/ +function isZodV4Schema(v) { + return typeof v === "object" && v !== null && "_zod" in v; +} +function looksLikeZodV3(v) { + return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; +} +/** +* Detects a "raw shape" — a plain object whose values are Zod field schemas, +* e.g. `{ name: z.string() }`. Powers the auto-wrap in +* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only +* Zod values are supported. +* +* @internal +*/ +function isZodRawShape(obj) { + if (typeof obj !== "object" || obj === null) return false; + if (isStandardSchema(obj)) return false; + const proto = Object.getPrototypeOf(obj); + if (proto !== Object.prototype && proto !== null) return false; + return Object.values(obj).every((v) => isZodV4Schema(v)); +} +/** +* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape +* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. +* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a +* uniform schema type; already-wrapped schemas pass through unchanged. +* +* @internal +*/ +function normalizeRawShapeSchema(schema) { + if (schema === void 0) return void 0; + if (isZodRawShape(schema)) return schemas_object(schema); + if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); + if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); + return schema; +} + +//#endregion +//#region ../core-internal/src/wire/preload.ts +/** +* Explicit warm-up entry for the lazy wire-schema layers. +* +* The per-revision wire schemas are built lazily: each era's schema set sits +* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the +* registry/codec lookup maps above those factories are memoized the same way. +* That laziness is the right default on process-per-invocation runtimes (CLI +* tools, dev servers), where module evaluation IS startup latency and most +* short-lived processes never validate a message on both eras. +* +* On platforms that bill request CPU but not module evaluation — isolate-based +* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: +* module-scope work runs during isolate warm-up outside any request, while +* lazy construction lands inside the first request's billed (and latency +* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move +* the one-time construction cost back to module scope by calling it at module +* scope themselves. The packages' own workerd shims already do this, so +* Workers deployments get eager construction automatically. +*/ +/** +* Eagerly builds every lazily-constructed wire-schema layer, so that no later +* validation pays schema-construction cost. +* +* Synchronous and idempotent: every layer is a memo, so the first call does +* all the work and subsequent calls return immediately. Reference identity is +* unaffected — this forces the same memos every lazy consumer pulls through. +* +* Call it at module scope on platforms that bill per-request CPU but not +* module evaluation (isolate-based edge/serverless runtimes), where deferring +* construction would move it into the first request of every fresh isolate: +* +* ```ts +* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — +* // each package bundles its own schema copy, so warm the one(s) you import. +* preloadSchemas(); // module scope — runs during isolate warm-up +* ``` +* +* On Node CLIs and other process-per-invocation runtimes, prefer the lazy +* default — there, module-scope construction is pure added boot latency. +*/ +function preloadSchemas() { + buildSchemas2025(); + buildSchemas2026(); + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} + +//#endregion +//#region ../core-internal/src/validators/fromJsonSchema.ts +/** +* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be +* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON +* Schema (e.g. from TypeBox, or hand-written) and want to register it without going +* through a Standard Schema library. +* +* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript +* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. +* +* @param schema - A JSON Schema object describing the expected shape +* @param validator - A validator provider. When importing `fromJsonSchema` from +* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate +* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). +* +* @example +* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" +* const inputSchema = fromJsonSchema<{ name: string }>( +* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, +* validator +* ); +* // Use with server.registerTool('greet', { inputSchema }, handler) +* ``` +*/ +function fromJsonSchema(schema, validator) { + const check = validator.getValidator(schema); + return { "~standard": { + version: 1, + vendor: "mcp", + jsonSchema: { + input: () => schema, + output: () => schema + }, + validate: (data) => { + const result = check(data); + return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; + } + } }; +} + +//#endregion + +//# sourceMappingURL=src-CX2iR2pK.mjs.map + + + +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = require_code$1(); + const scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = require_codegen(); + const code_1 = require_code$1(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const names = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = require_rules(); + const applicability_1 = require_applicability(); + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const code_1 = require_code(); + const errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a$1; + gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0;) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + const util_1 = require_util(); + const equal = require_fast_deep_equal(); + const traverse = require_json_schema_traverse(); + const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + const TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + const boolSchema_1 = require_boolSchema(); + const dataType_1 = require_dataType(); + const applicability_1 = require_applicability(); + const dataType_2 = require_dataType(); + const defaults_1 = require_defaults(); + const keyword_1 = require_keyword(); + const subschema_1 = require_subschema(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + const codegen_1 = require_codegen(); + const validation_error_1 = require_validation_error(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { "$data": { + "type": "string", + "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] + } }, + "additionalProperties": false + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** @type {(value: string) => boolean} */ + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + /** @type {(value: string) => boolean} */ + const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + /** + * @param {Array} input + * @returns {string} + */ + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + /** + * @typedef {Object} GetIPV6Result + * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. + * @property {string} address - The parsed IPv6 address. + * @property {string} [zone] - The zone identifier, if present. + */ + /** + * @param {string} value + * @returns {boolean} + */ + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + /** + * @param {Array} buffer + * @returns {boolean} + */ + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + /** + * @param {Array} buffer + * @param {Array} address + * @param {GetIPV6Result} output + * @returns {boolean} + */ + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") address.push(hex); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + /** + * @param {string} input + * @returns {GetIPV6Result} + */ + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + /** @type {Array} */ + const address = []; + /** @type {Array} */ + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + /** + * @typedef {Object} NormalizeIPv6Result + * @property {string} host - The normalized host. + * @property {string} [escapedHost] - The escaped host. + * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. + */ + /** + * @param {string} host + * @returns {NormalizeIPv6Result} + */ + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + /** + * @param {string} str + * @param {string} token + * @returns {number} + */ + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + /** + * @param {string} path + * @returns {string} + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + /** + * @param {import('../types/index').URIComponent} component + * @param {boolean} esc + * @returns {import('../types/index').URIComponent} + */ + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) component.scheme = func(component.scheme); + if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); + if (component.host !== void 0) component.host = func(component.host); + if (component.path !== void 0) component.path = func(component.path); + if (component.query !== void 0) component.query = func(component.query); + if (component.fragment !== void 0) component.fragment = func(component.fragment); + return component; + } + /** + * @param {import('../types/index').URIComponent} component + * @returns {string|undefined} + */ + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = component.host; + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { isUUID } = require_utils(); + const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + const supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + /** @typedef {supportedSchemeNames[number]} SchemeName */ + /** + * @param {string} name + * @returns {name is SchemeName} + */ + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + /** + * @callback SchemeFn + * @param {import('../types/index').URIComponent} component + * @param {import('../types/index').Options} options + * @returns {import('../types/index').URIComponent} + */ + /** + * @typedef {Object} SchemeHandler + * @property {SchemeName} scheme - The scheme name. + * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. + * @property {SchemeFn} parse - Function to parse the URI component for this scheme. + * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. + * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. + * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. + * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. + */ + /** + * @param {import('../types/index').URIComponent} wsComponent + * @returns {boolean} + */ + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + /** @type {SchemeFn} */ + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + /** @type {SchemeFn} */ + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + /** @type {SchemeFn} */ + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + /** @type {SchemeFn} */ + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + /** @type {SchemeFn} */ + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + /** @type {SchemeFn} */ + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + const http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + const https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + const ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + const wss = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }; + const urn = { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }; + const urnuuid = { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + }; + const SCHEMES = { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + }; + Object.setPrototypeOf(SCHEMES, null); + /** + * @param {string|undefined} scheme + * @returns {SchemeHandler|undefined} + */ + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + /** + * @template {import('./types/index').URIComponent|string} T + * @param {T} uri + * @param {import('./types/index').Options} [options] + * @returns {T} + */ + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse(uri, options), options); + else if (typeof uri === "object") uri = parse(serialize(uri, options), options); + return uri; + } + /** + * @param {string} baseURI + * @param {string} relativeURI + * @param {import('./types/index').Options} [options] + * @returns {string} + */ + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + /** + * @param {import ('./types/index').URIComponent} base + * @param {import ('./types/index').URIComponent} relative + * @param {import('./types/index').Options} [options] + * @param {boolean} [skipNormalization=false] + * @returns {import ('./types/index').URIComponent} + */ + function resolveComponent(base, relative, options, skipNormalization) { + /** @type {import('./types/index').URIComponent} */ + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); + relative = parse(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + /** + * @param {import ('./types/index').URIComponent|string} uriA + * @param {import ('./types/index').URIComponent|string} uriB + * @param {import ('./types/index').Options} options + * @returns {boolean} + */ + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { + ...options, + skipEscape: true + }); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + /** + * @param {Readonly} cmpts + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = unescape(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns + */ + function parse(uri, opts) { + const options = Object.assign({}, opts); + /** @type {import('./types/index').URIComponent} */ + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = unescape(parsed.host); + } + if (parsed.path) parsed.path = escape(unescape(parsed.path)); + if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return parsed; + } + const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + const validation_error_1 = require_validation_error(); + const ref_error_1 = require_ref_error(); + const rules_1 = require_rules(); + const compile_1 = require_compile(); + const codegen_2 = require_codegen(); + const resolve_1 = require_resolve(); + const dataType_1 = require_dataType(); + const util_1 = require_util(); + const $dataRefSchema = require_data(); + const uri_1 = require_uri(); + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + const removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: "\"nullable\" keyword is supported by default.", + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: "\"uniqueItems\" keyword is always validated.", + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + const MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + const ref_error_1 = require_ref_error(); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const util_1 = require_util(); + const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const id_1 = require_id(); + const ref_1 = require_ref(); + const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const ucs2length_1 = require_ucs2length(); + const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const util_1 = require_util(); + const codegen_1 = require_codegen(); + const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dataType_1 = require_dataType(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const limitNumber_1 = require_limitNumber(); + const multipleOf_1 = require_multipleOf(); + const limitLength_1 = require_limitLength(); + const pattern_1 = require_pattern(); + const limitProperties_1 = require_limitProperties(); + const required_1 = require_required(); + const limitItems_1 = require_limitItems(); + const uniqueItems_1 = require_uniqueItems(); + const const_1 = require_const(); + const enum_1 = require_enum(); + const validation = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; + exports.default = validation; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const items_1 = require_items(); + const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const additionalItems_1 = require_additionalItems(); + const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const util_1 = require_util(); + const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const validate_1 = require_validate(); + const code_1 = require_code(); + const util_1 = require_util(); + const additionalProperties_1 = require_additionalProperties(); + const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const util_2 = require_util(); + const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const additionalItems_1 = require_additionalItems(); + const prefixItems_1 = require_prefixItems(); + const items_1 = require_items(); + const items2020_1 = require_items2020(); + const contains_1 = require_contains(); + const dependencies_1 = require_dependencies(); + const propertyNames_1 = require_propertyNames(); + const additionalProperties_1 = require_additionalProperties(); + const properties_1 = require_properties(); + const patternProperties_1 = require_patternProperties(); + const not_1 = require_not(); + const anyOf_1 = require_anyOf(); + const oneOf_1 = require_oneOf(); + const allOf_1 = require_allOf(); + const if_1 = require_if(); + const thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$2().default]; + exports.default = format; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const types_1 = require_types(); + const compile_1 = require_compile(); + const ref_error_1 = require_ref_error(); + const util_1 = require_util(); + const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const discriminator_1 = require_discriminator(); + const draft7MetaSchema = require_json_schema_draft_07(); + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js +var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicAnchor = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema) + }; + function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); + } + exports.dynamicAnchor = dynamicAnchor; + function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js +var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicRef = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema) + }; + function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) _dynamicRef(); + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } else _callRef(it.validateName, valid)(); + } + function _callRef(validate, valid) { + return valid ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) : () => (0, ref_1.callRef)(cxt, validate); + } + } + exports.dynamicRef = dynamicRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js +var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const util_1 = require_util(); + const def = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js +var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicRef_1 = require_dynamicRef(); + const def = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js +var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const dynamicRef_1 = require_dynamicRef(); + const recursiveAnchor_1 = require_recursiveAnchor(); + const recursiveRef_1 = require_recursiveRef(); + const dynamic = [ + dynamicAnchor_1.default, + dynamicRef_1.default, + recursiveAnchor_1.default, + recursiveRef_1.default + ]; + exports.default = dynamic; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js +var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js +var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js +var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js +var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependentRequired_1 = require_dependentRequired(); + const dependentSchemas_1 = require_dependentSchemas(); + const limitContains_1 = require_limitContains(); + const next = [ + dependentRequired_1.default, + dependentSchemas_1.default, + limitContains_1.default + ]; + exports.default = next; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js +var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const def = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` + }, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + it.props = true; + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); + return (0, codegen_1.and)(...ps); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js +var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) return; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._)`${len} > ${items}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ + keyword: "unevaluatedItems", + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js +var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const unevaluatedProperties_1 = require_unevaluatedProperties(); + const unevaluatedItems_1 = require_unevaluatedItems(); + const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; + exports.default = unevaluated; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "meta/validation#/$defs/stringArray" }] } + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, + "$recursiveAnchor": true, + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": { "$recursiveRef": "#" }, + "unevaluatedItems": { "$recursiveRef": "#" }, + "items": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "#/$defs/schemaArray" }] }, + "contains": { "$recursiveRef": "#" }, + "additionalProperties": { "$recursiveRef": "#" }, + "unevaluatedProperties": { "$recursiveRef": "#" }, + "properties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" } + }, + "propertyNames": { "$recursiveRef": "#" }, + "if": { "$recursiveRef": "#" }, + "then": { "$recursiveRef": "#" }, + "else": { "$recursiveRef": "#" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$recursiveRef": "#" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$recursiveRef": "#" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json +var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, + "$recursiveAnchor": true, + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json +var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json +var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, + "$recursiveAnchor": true, + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js +var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema$1(); + const applicator = require_applicator$1(); + const content = require_content$1(); + const core = require_core$1(); + const format = require_format(); + const metadata = require_meta_data$1(); + const validation = require_validation$1(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2019($data) { + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2019; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js +var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const discriminator_1 = require_discriminator(); + const json_schema_2019_09_1 = require_json_schema_2019_09(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; + var Ajv2019 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2019 = Ajv2019; + module.exports = exports = Ajv2019; + module.exports.Ajv2019 = Ajv2019; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2019; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js +var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default + ]; + exports.default = draft2020Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json +var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/unevaluated" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format-annotation" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { "anyOf": [{ "$dynamicRef": "#meta" }, { "$ref": "meta/validation#/$defs/stringArray" }] }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, + "$dynamicAnchor": "meta", + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": { "$ref": "#/$defs/schemaArray" }, + "items": { "$dynamicRef": "#meta" }, + "contains": { "$dynamicRef": "#meta" }, + "additionalProperties": { "$dynamicRef": "#meta" }, + "properties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "propertyNames": { "$dynamicRef": "#meta" }, + "if": { "$dynamicRef": "#meta" }, + "then": { "$dynamicRef": "#meta" }, + "else": { "$dynamicRef": "#meta" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$dynamicRef": "#meta" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$dynamicRef": "#meta" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json +var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json +var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json +var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, + "$dynamicAnchor": "meta", + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { "$ref": "#/$defs/uriString" }, + "$ref": { "$ref": "#/$defs/uriReferenceString" }, + "$anchor": { "$ref": "#/$defs/anchorString" }, + "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, + "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, + "$vocabulary": { + "type": "object", + "propertyNames": { "$ref": "#/$defs/uriString" }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" } + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json +var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json +var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json +var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, + "$dynamicAnchor": "meta", + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js +var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema(); + const applicator = require_applicator(); + const unevaluated = require_unevaluated(); + const content = require_content(); + const core = require_core(); + const format = require_format_annotation(); + const metadata = require_meta_data(); + const validation = require_validation(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2020; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js +var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; + const core_1 = require_core$3(); + const draft2020_1 = require_draft2020(); + const discriminator_1 = require_discriminator(); + const json_schema_2020_12_1 = require_json_schema_2020_12(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + var Ajv2020 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2020 = Ajv2020; + module.exports = exports = Ajv2020; + module.exports.Ajv2020 = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + byte, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + const DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date(str) { + const matches = DATE.exec(str); + if (!matches) return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + const DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + const NOT_URI_FRAGMENT = /\/|:/; + const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + const MIN_INT32 = -(2 ** 31); + const MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + const Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + const ajv_1 = require_ajv(); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const formats_1 = require_formats(); + const limit_1 = require_limit(); + const codegen_1 = require_codegen(); + const fullName = new codegen_1.Name("fullFormats"); + const fastName = new codegen_1.Name("fastFormats"); + const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); + +//#endregion +//#region ../core-internal/src/validators/ajvProvider.ts +var import_ajv = require_ajv(); +var import__2019 = require__2019(); +var import__2020 = require__2020(); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ +const ajvProvider_CEoC_sr_addFormats = import_dist.default; +function createDefaultAjvInstance(engineClass) { + const ajv = new engineClass({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + ajvProvider_CEoC_sr_addFormats(ajv); + return ajv; +} +/** +* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` +* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). +* +* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` +* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class +* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv +* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching +* v1's default engine), while the cfworker provider ignores them per spec. +* Schemas declaring any other `$schema` are +* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate +* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type +* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 +* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and +* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would +* silently downgrade dialect. +* +* @example Use with default configuration +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" +* const validator = new AjvJsonSchemaValidator(); +* ``` +* +* @example Use with a custom AJV instance +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +* +* @example Register ajv-formats +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +*/ +var AjvJsonSchemaValidator = class { + _ajv; + /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ + _ajvDraft7; + /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ + _ajv2019; + /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ + _userAjv; + /** + * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is + * used for **every** schema regardless of its declared `$schema` (the caller owns dialect + * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, + * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. + */ + constructor(ajv) { + this._userAjv = ajv !== void 0; + this._ajv = ajv; + } + /** The underlying 2020-12 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); + } + /** + * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for + * every schema — do not second-guess by `$schema` (bring-your-own-validator means + * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → + * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. + */ + _engineFor(schema) { + if (this._userAjv) return this.ajv; + const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); + if (dialect === "2020-12") return this.ajv; + if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); + return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); + } + getValidator(schema) { + const engine = this._engineFor(schema); + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); + return (input) => { + return ajvValidator(input) ? { + valid: true, + data: input, + errorMessage: void 0 + } : { + valid: false, + data: void 0, + errorMessage: engine.errorsText(ajvValidator.errors) + }; + }; + } +}; +/** +* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. +* The full v1-equivalent construction is: +* +* ```ts +* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* new AjvJsonSchemaValidator(ajv); +* ``` +* +* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque +* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` +* validation that the v1 default had). +* +* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream +* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own +* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. +*/ +const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; + +//#endregion + +//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map + + + + + + + + +//#region src/server/completable.ts +const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); +/** +* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. +* +* @example +* ```ts source="./completable.examples.ts#completable_basicUsage" +* server.registerPrompt( +* 'review-code', +* { +* title: 'Code Review', +* argsSchema: z.object({ +* language: completable(z.string().describe('Programming language'), value => +* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) +* ) +* }) +* }, +* ({ language }) => ({ +* messages: [ +* { +* role: 'user' as const, +* content: { +* type: 'text' as const, +* text: `Review this ${language} code.` +* } +* } +* ] +* }) +* ); +* ``` +* +* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions +*/ +function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** +* Checks if a schema is completable (has completion metadata). +*/ +function isCompletable(schema) { + return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; +} +/** +* Gets the completer callback from a completable schema, if it exists. +*/ +function getCompleter(schema) { + return schema[COMPLETABLE_SYMBOL]?.complete; +} + +//#endregion +//#region src/server/sseKeepAlive.ts +/** Default interval between SSE keep-alive comment frames. */ +const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; +const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); +/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ +function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { + if (!Number.isFinite(intervalMs) || intervalMs < 1) return; + const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); + timer.unref?.(); + return timer; +} + +//#endregion +//#region src/server/serverEventBus.ts +/** +* A `ServerEventBus` backed by an in-process listener set. +* +* `publish()` delivers synchronously to the live listener set (a listener +* unsubscribing itself mid-dispatch is safe; the entry's listen-router +* listeners never unsubscribe peers). A throwing listener does not stop +* delivery to the others. +*/ +var mcp_DXXb3Vv3_InMemoryServerEventBus = class { + _listeners = /* @__PURE__ */ new Set(); + /** + * @param onerror - Optional callback for errors thrown by listeners + * during dispatch. + */ + constructor(onerror) { + this.onerror = onerror; + } + publish(event) { + for (const listener of this._listeners) try { + listener(event); + } catch (error) { + this.onerror?.(error instanceof Error ? error : new Error(String(error))); + } + } + subscribe(listener) { + this._listeners.add(listener); + let live = true; + return () => { + if (!live) return; + live = false; + this._listeners.delete(listener); + }; + } + /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ + get listenerCount() { + return this._listeners.size; + } +}; +/** Build a {@linkcode ServerNotifier} over a bus. */ +function mcp_DXXb3Vv3_createServerNotifier(bus) { + return { + toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), + promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), + resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), + resourceUpdated: (uri) => bus.publish({ + kind: "resource_updated", + uri + }) + }; +} +/** +* Whether a `subscriptions/listen` filter accepts a given change event. +* +* Pure: no I/O, no mutation. The filter governs ONLY the four +* subscription-gated change types — non-gated notifications never reach the +* bus and are not modeled here. +* +* `resource_updated` matches only when `resourceSubscriptions` is present and +* contains the event's URI exactly (per the spec: "for these resource URIs"). +*/ +function listenFilterAccepts(filter, event) { + switch (event.kind) { + case "tools_list_changed": return filter.toolsListChanged === true; + case "prompts_list_changed": return filter.promptsListChanged === true; + case "resources_list_changed": return filter.resourcesListChanged === true; + case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); + } +} +/** +* The honored subset of a requested filter: keeps only the fields the client +* explicitly opted in to (drops `false` and absent fields), narrowed against +* the server's declared capabilities when supplied. The serving entry sends +* this back in `notifications/subscriptions/acknowledged` so the ack reflects +* what the server can actually deliver. +* +* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` +* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. +* - `resourceSubscriptions` is honored only when +* `capabilities.resources.subscribe` is advertised. +* +* `capabilities` is optional on this pure helper for test convenience only — +* both wired routers REQUIRE capabilities at the call site (the HTTP router's +* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws +* before `setServerCapabilities()` was called), so the fail-open +* `undefined → honor everything` branch is never reachable on a wired entry. +*/ +function honoredSubset(requested, capabilities) { + const honored = {}; + const allow = (bit) => capabilities === void 0 || bit === true; + if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; + if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; + if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; + if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; + return honored; +} +/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ +function serverEventToNotification(event) { + switch (event.kind) { + case "tools_list_changed": return { method: "notifications/tools/list_changed" }; + case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; + case "resources_list_changed": return { method: "notifications/resources/list_changed" }; + case "resource_updated": return { + method: "notifications/resources/updated", + params: { uri: event.uri } + }; + } +} + +//#endregion +//#region src/server/listenRouter.ts +/** Default capacity guard: refuse a new subscription when this many are already open. */ +const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; +function jsonRpcError(id, code, message) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message + }, + id + }, { status: 200 }); +} +/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ +function stampSubscriptionId(notification, subscriptionId) { + return { + method: notification.method, + params: { + ...notification.params, + _meta: { + ...notification.params?._meta, + [SUBSCRIPTION_ID_META_KEY]: subscriptionId + } + } + }; +} +/** +* Read the requested filter off a `subscriptions/listen` request body. +* Returns the validated filter, or `undefined` when `params.notifications` +* is absent or fails the schema (the caller answers `-32602` — the spec +* marks `notifications` REQUIRED on the listen request). +*/ +function parseListenFilter(message) { + const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); + return outcome.ok ? outcome.value.params?.notifications : void 0; +} +function mcp_DXXb3Vv3_createListenRouter(options) { + const { bus, onerror } = options; + const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; + const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; + const open = /* @__PURE__ */ new Set(); + function serve(message, signal, capabilities, serverInfo) { + if (open.size >= maxSubscriptions) { + onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); + return jsonRpcError(message.id, -32603, "Subscription limit reached"); + } + const filter = parseListenFilter(message); + if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); + const honored = honoredSubset(filter, capabilities); + const subscriptionId = message.id; + const encoder = new TextEncoder(); + let controller; + let closed = false; + let unsubscribe; + let keepAliveTimer; + let abortCleanup; + const writeFrame = (frame) => { + if (closed) return; + try { + controller.enqueue(encoder.encode(frame)); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + }; + const writeNotification = (method, params) => { + writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + method, + params + })}\n\n`); + }; + const teardown = (graceful) => { + if (closed) return; + if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: subscriptionId, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: subscriptionId, + [SERVER_INFO_META_KEY]: serverInfo + } + } + })}\n\n`); + closed = true; + try { + unsubscribe?.(); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + abortCleanup?.(); + open.delete(teardown); + try { + controller.close(); + } catch {} + }; + const readable = new ReadableStream({ + start(streamController) { + controller = streamController; + const ack = stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, subscriptionId); + writeNotification(ack.method, ack.params); + unsubscribe = bus.subscribe((event) => { + if (closed || !listenFilterAccepts(honored, event)) return; + const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); + writeNotification(note.method, note.params); + }); + keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); + open.add(teardown); + }, + cancel() { + teardown(false); + } + }); + if (signal !== void 0) if (signal.aborted) teardown(false); + else { + const onAbort = () => teardown(false); + signal.addEventListener("abort", onAbort, { once: true }); + abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + return new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + }); + } + return { + serve, + closeAll() { + for (const teardown of open) teardown(true); + }, + get openCount() { + return open.size; + } + }; +} +const CHANGE_NOTIFICATION_METHODS = new Set([ + "notifications/tools/list_changed", + "notifications/prompts/list_changed", + "notifications/resources/list_changed", + "notifications/resources/updated" +]); +/** +* Per-connection listen state for the stdio entry. One instance is held by +* `serveStdio` for the connection lifetime; it routes inbound +* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound +* change notifications onto the active subscriptions. No bus — the long-lived +* pinned instance's existing `send*ListChanged()` calls feed straight into +* `routeOutbound()`. +*/ +var mcp_DXXb3Vv3_StdioListenRouter = class { + /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ + _subs = /* @__PURE__ */ new Map(); + /** + * The serving instance's declared capabilities. Filled in by the entry + * once the modern instance is constructed (the router is created before + * the instance exists), so the acknowledged filter is narrowed against + * what the server can actually deliver. + */ + _serverCapabilities; + /** + * The serving instance's identity, stamped onto the graceful-close + * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends + * `ResultMetaObject`). Handed over together with the capabilities. + */ + _serverInfo; + constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { + this._maxSubscriptions = _maxSubscriptions; + this._serverCapabilities = serverCapabilities; + this._serverInfo = serverInfo; + } + /** + * Record the serving instance's declared capabilities and identity once + * it has been constructed. Called by `serveStdio`'s connect path; + * subsequent `serve()` calls narrow the honored filter against the + * capabilities, and `teardownAll()` stamps the identity. + */ + setServerCapabilities(capabilities, serverInfo) { + this._serverCapabilities = capabilities; + if (serverInfo !== void 0) this._serverInfo = serverInfo; + } + /** Whether `id` is an active listen subscription on this connection. */ + has(id) { + return this._subs.has(id); + } + /** + * Serve one inbound `subscriptions/listen` request: registers the + * subscription and returns the stamped acknowledged notification (or, on + * capacity / params rejection, the in-band JSON-RPC error response). + * + * @throws when called before {@linkcode setServerCapabilities} (or the + * constructor) has supplied the serving instance's capabilities. Honoring a + * filter without knowing the server's advertised capabilities would fail + * open (deliver unadvertised types); the entry guarantees capabilities are + * set before any listen request is routed here. + */ + serve(message) { + if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); + if (this._subs.size >= this._maxSubscriptions) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32603, + message: "Subscription limit reached" + } + }; + const filter = parseListenFilter(message); + if (filter === void 0) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" + } + }; + const honored = honoredSubset(filter, this._serverCapabilities); + this._subs.set(message.id, honored); + return stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, message.id); + } + /** + * Tear down one subscription (inbound `notifications/cancelled`). Returns + * `true` when a subscription was removed. After this call NOTHING further + * is delivered for that subscription id (the post-cancel hardening). + */ + cancel(id) { + return this._subs.delete(id); + } + /** + * Route an outbound notification through the active subscriptions. + * + * - For a subscription-gated change notification, returns one stamped copy + * per subscription that opted in to it (an empty array means it is + * dropped — the modern era never delivers an un-requested change type). + * - For any other outbound message, returns `'passthrough'` (the entry + * forwards it as-is). + */ + routeOutbound(message) { + if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; + const uriParam = message.params?.["uri"]; + const uri = typeof uriParam === "string" ? uriParam : void 0; + const event = notificationToServerEvent(message.method, uri); + const out = []; + for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ + method: message.method, + params: message.params ?? {} + }, subscriptionId)); + return out; + } + /** + * Server-side graceful teardown of every active subscription: returns the + * empty `subscriptions/listen` JSON-RPC result for each subscription id — + * the spec's graceful-close signal, `_meta` carrying the subscription id + * and the serving instance's identity — for the entry to emit before + * closing the wire. Clears the set so nothing further is delivered. + */ + teardownAll() { + const out = []; + for (const id of this._subs.keys()) out.push({ + jsonrpc: "2.0", + id, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: id, + ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } + } + } + }); + this._subs.clear(); + return out; + } +}; +function notificationToServerEvent(method, uri) { + switch (method) { + case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; + case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; + case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; + default: return { + kind: "resource_updated", + uri: uri ?? "" + }; + } +} + +//#endregion +//#region src/server/legacyInputRequiredShim.ts +/** +* Default handler re-entries per originating request — tighter than the +* client driver's 10 because the shim holds a live wire request open. +*/ +const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; +/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ +const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; +/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ +function resolveLegacyShimOptions(options) { + if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); + if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); + return { + maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, + roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, + legacyShim: options?.legacyShim ?? true + }; +} +/** +* Validates one `inputRequests` entry: malformed or unknown kinds are server +* bugs and fail loudly on both eras. Shared by the modern seam's capability +* check and the shim's gate. +*/ +function coerceEmbeddedInputRequest(method, key, entry) { + if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); + const embedded = entry; + const required = requiredClientCapabilitiesForInputRequest(embedded); + if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); + return { + embedded, + required + }; +} +/** +* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 +* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a +* getRandomValues fallback for runtimes without `randomUUID`). +*/ +function syntheticElicitationId() { + const webCrypto = globalThis.crypto; + if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); + const bytes = new Uint8Array(16); + webCrypto.getRandomValues(bytes); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ +function legacyShimFailure(method, message) { + if (method === "tools/call") return { + content: [{ + type: "text", + text: message + }], + isError: true + }; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); +} +/** The fulfilment loop — see the module doc for the contract. */ +var LegacyInputRequiredShim = class { + constructor(_host) { + this._host = _host; + } + async fulfill(method, handler, request, ctx, firstResult) { + const { maxRounds, roundTimeoutMs } = this._host; + const outerSignal = ctx.mcpReq.signal; + let current = firstResult; + let round = 0; + while (true) { + round += 1; + if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); + const inputRequests = current.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const requestState = typeof current.requestState === "string" ? current.requestState : void 0; + if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + let responses; + if (hasInputRequests) { + const declared = this._host.resolvedClientCapabilities(ctx); + const coerced = []; + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); + if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); + coerced.push([key, embedded]); + } + const roundAbort = linkedRoundAbort(outerSignal); + try { + const legOptions = { + relatedRequestId: ctx.mcpReq.id, + timeout: roundTimeoutMs, + resetTimeoutOnProgress: true, + onprogress: () => {}, + signal: roundAbort.signal + }; + const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { + try { + return [key, await this._dispatchLeg(embedded, legOptions)]; + } catch (error) { + roundAbort.abort(error); + throw error; + } + })); + responses = Object.fromEntries(fulfilled); + } catch (error) { + if (outerSignal.aborted) throw error; + return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); + } finally { + roundAbort.dispose(); + } + } else await sleep((/* inlined export .C */250), outerSignal); + let ctxNext = { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + inputResponses: responses, + droppedInputResponseKeys: void 0, + requestState: requestStateAccessor(requestState) + } + }; + if (requestState !== void 0) { + const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); + if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); + } + const next = await handler(request, ctxNext); + if (!isInputRequiredResult(next)) return next; + current = next; + } + } + /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ + async _dispatchLeg(embedded, options) { + switch (embedded.method) { + case "elicitation/create": { + let params = embedded.params; + if (params.mode === "url" && params.elicitationId === void 0) params = { + ...params, + elicitationId: syntheticElicitationId() + }; + return await this._host.sendElicitation(params, options); + } + case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); + case "roots/list": return await this._host.listRoots(embedded.params, options); + } + } +}; + +//#endregion +//#region src/server/server.ts +/** +* The request methods whose 2026-07-28 result vocabulary includes +* `input_required` (the multi round-trip methods). Returning an +* input-required result from any other handler is a server bug. +*/ +const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ + "tools/call", + "prompts/get", + "resources/read" +]); +let writeClientIdentity; +let installDiscoverHandler; +let readServerIdentity; +/** +* Package-internal: backfills the connection-scoped client-identity fields of a +* per-request server instance from the request's validated `_meta` envelope, so the +* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} +* accessors keep answering on instances that never see an `initialize` handshake. +* Not public API. +*/ +function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { + writeClientIdentity(server, identity); +} +/** +* Package-internal: installs the modern-only `server/discover` handler on an instance +* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern +* revisions the entry serves appear in the instance's supported-versions list (so the +* discover advertisement and version-mismatch errors name them). Idempotent. +* Hand-constructed instances are unaffected: nothing else calls this, so they keep +* answering `-32601` unless their own supported-versions list opts into a modern +* revision. Not public API. +*/ +function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { + installDiscoverHandler(server, servedModernVersions); +} +/** +* Package-internal: the instance's implementation identity, for the serving +* entries to stamp onto entry-built results (the `subscriptions/listen` +* graceful-close result — built outside the encode seam, but the spec's +* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries +* the serverInfo SHOULD like every other result). Not public API. +*/ +function mcp_DXXb3Vv3_serverIdentityOf(server) { + return readServerIdentity(server); +} +/** +* An MCP server on top of a pluggable transport. +* +* This server will automatically respond to the initialization flow as initiated from the client. +* +* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. +*/ +var Server = class extends Protocol { + _clientCapabilities; + _clientVersion; + static { + writeClientIdentity = (server, identity) => { + if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; + if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; + }; + installDiscoverHandler = (server, servedModernVersions) => { + const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); + if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; + server.setRequestHandler("server/discover", () => server._ondiscover()); + }; + readServerIdentity = (server) => server._serverInfo; + } + _capabilities; + _instructions; + _jsonSchemaValidator; + _cacheHints; + _requestStateVerify; + _inputRequiredServing; + _legacyShim; + /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ + _legacyInputRequiredShim() { + return this._legacyShim ??= new LegacyInputRequiredShim({ + maxRounds: this._inputRequiredServing.maxRounds, + roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, + resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), + verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), + sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), + sendSampling: (params, options) => this.createMessage(params, options), + listRoots: (params, options) => this.listRoots(params, options) + }); + } + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). + */ + oninitialized; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._requestStateVerify = options?.requestState?.verify; + this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); + if (options?.cacheHints !== void 0) { + for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); + this._cacheHints = options.cacheHints; + } + this.setRequestHandler("initialize", (request) => this._oninitialize(request)); + this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); + if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); + if (this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Registers the built-in `logging/setLevel` request handler. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + _registerLoggingHandler() { + this.setRequestHandler("logging/setLevel", async (request, ctx) => { + const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; + const { level } = request.params; + const parseResult = parseSchema(LoggingLevelSchema, level); + if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); + return {}; + }); + } + buildContext(ctx, transportInfo) { + const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + log: (level, data, logger) => { + if (!this._capabilities.logging) return Promise.resolve(); + let threshold; + if (this._servedModernEra()) { + threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; + if (threshold === void 0) return Promise.resolve(); + } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); + if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); + return ctx.mcpReq.notify({ + method: "notifications/message", + params: { + level, + data, + logger + } + }); + }, + elicitInput: (params, options) => this.elicitInput(params, options), + requestSampling: (params, options) => this.createMessage(params, options) + }, + http: hasHttpInfo ? { + ...ctx.http, + req: transportInfo?.request, + closeSSE: transportInfo?.closeSSEStream, + closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream + } : void 0 + }; + } + _loggingLevels = /* @__PURE__ */ new Map(); + LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); + const hadLogging = !!this._capabilities.logging; + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Enforces server-side validation for `tools/call` results regardless of how the + * handler was registered, attaches the configured per-operation cache hint + * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` + * for results that do not provide their own, and owns the multi-round-trip + * seam: on the methods whose 2026-07-28 result vocabulary includes + * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an + * input-required return skips result-schema validation and is checked + * against the served era, the at-least-one rule, and the request's own + * declared client capabilities; on every other method an input-required + * return is a server bug and fails loudly. The hint rides a symbol-keyed + * property that is never serialized, so 2025-era responses are unaffected. + */ + _wrapHandler(method, handler) { + if (method !== "tools/call") { + const cacheHint = this._cacheHints?.[method]; + const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); + if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { + const result = await handler(request, ctx); + if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + }; + return async (request, ctx) => { + const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); + if (isInputRequiredResult(result)) { + if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + } + return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); + }; + } + return async (request, ctx) => { + const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + const validatedRequest = codec.validateRequest("tools/call", request); + if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); + const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); + if (isInputRequiredResult(result)) return result; + const normalizedResult = normalizeContentlessToolResult(result); + const validationResult = codec.validateResult("tools/call", normalizedResult); + if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); + return validationResult.value; + }; + } + /** + * Whether this instance is bound to a 2026-07-28-or-later protocol + * revision. Era is instance state — a serving entry (`createMcpHandler`, + * `serveStdio`) marks the instance modern at construction; a 2025-era + * `initialize` handshake binds it legacy. The multi-round-trip seam reads + * this directly: there is no per-request era consult. + */ + _servedModernEra() { + return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); + } + /** + * Invokes a handler for one of the multi-round-trip methods and applies + * the input-required seam: + * + * - a `UrlElicitationRequiredError` (or any 2025-style server→client + * request idiom) escaping the handler on a request served on the + * 2026-07-28 era fails LOUDLY with a clear steer to + * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the + * 2026-07-28 wire and the throw is not silently converted. Requests + * served on the 2025 era keep today's `-32042` behavior byte-exact (the + * error is rethrown unchanged). + * - an input-required RETURN toward a 2026-07-28 request must satisfy + * the at-least-one rule, and every embedded request must be covered by + * the capabilities declared on the request's envelope (violations + * answer the typed `-32021` error). Toward a 2025-era request the + * return is fulfilled by the default-on legacy shim, whose own gate + * consults the initialize-declared capabilities and surfaces + * violations per family; `inputRequired.legacyShim: false` restores + * the pre-shim loud failure. + */ + async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { + const servedModern = this._servedModernEra(); + const rawRequestState = ctx.mcpReq.requestState(); + if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + let ctxForHandler = ctx; + if (typeof rawRequestState === "string") { + const decoded = await this._verifyRequestState(rawRequestState, ctx, method); + if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); + } + let result; + try { + result = await handler(request, ctxForHandler); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { + if (!servedModern) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); + } + throw error; + } + if (!isInputRequiredResult(result)) return result; + if (!servedModern) { + if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); + return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); + } + const inputRequests = result.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const hasRequestState = typeof result.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + if (hasInputRequests) { + const declared = this._inputRequestCapabilityView(ctx); + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); + if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); + } + } + return result; + } + /** + * Runs the configured `requestState.verify` hook and returns its + * resolved value (`undefined` when unconfigured or the hook returns + * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; + * the reason goes to `onerror` only. + */ + async _verifyRequestState(state, ctx, method) { + if (this._requestStateVerify === void 0) return; + try { + return await this._requestStateVerify(state, ctx); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + } + } + /** + * The per-request resolved client-capabilities view: the request's own + * `_meta` envelope on the 2026 era; the `initialize`-declared state on a + * 2025-era connection. Per-request instances that never saw an + * initialize (stateless legacy) hold nothing, so gates refuse there. + */ + _inputRequestCapabilityView(ctx) { + return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; + } + /** + * Guard for the push-style server→client request APIs ({@linkcode createMessage}, + * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a + * modern-era instance: the 2026-07-28 revision has no server→client request + * channel, so the call fails before any wire traffic with a typed error + * whose message steers to `inputRequired(...)`. The base era gate would + * also reject it; this guard runs first to carry the steer. + */ + _assertPushApiInServedEra(method) { + if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { + method, + era: "2026-07-28" + }); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); + break; + case "roots/list": + if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); + break; + case "ping": break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); + break; + case "notifications/cancelled": break; + case "notifications/progress": break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "logging/setLevel": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "ping": + case "initialize": break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; + this._negotiatedProtocolVersion = protocolVersion; + this.transport?.setProtocolVersion?.(protocolVersion); + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` + * lists only modern revisions (2025-era versions are negotiated via `initialize`); + * the capabilities are advertised as-is, listChanged/subscribe bits included + * (see {@linkcode discoverAdvertisedCapabilities}). + */ + _ondiscover() { + return { + supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), + capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * The identity the 2026-era encode seam stamps into every outbound + * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR + * #3002: servers SHOULD identify themselves on every response). + */ + _outboundServerInfo() { + return this._serverInfo; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * declared capabilities, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * name and version, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientVersion() { + return this._clientVersion; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * with the client (the version the server responded with during the initialize handshake), or + * `undefined` before initialization. + * + * @deprecated Read the protocol revision from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the + * request was sent for, while on 2025-era connections this accessor keeps returning the + * `initialize`-negotiated version. The accessor remains functional — instances serving the + * 2026-07-28 era report that revision. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * Project a `tools/call` result through this instance's negotiated wire + * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on + * the 2025 era the `{result:…}` wrap when `structuredContent` is a + * non-object value or the advertised `outputSchema` had a non-object root. + * Identity for object-shaped `structuredContent` on the 2026 era. + * + * `McpServer`'s built-in `tools/call` handler routes through this method. + * Low-level `setRequestHandler('tools/call', …)` authors call it + * themselves so the projection lives in one place (the codec) and the + * server-side handler stays era-blind. + * + * This is the only codec function exposed on `Server` — the full + * `WireCodec` is intentionally not part of the public surface. + */ + projectCallToolResult(result, advertisedOutputSchema) { + return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); + } + /** + * Returns the current server capabilities. + */ + getCapabilities() { + return this._capabilities; + } + /** + * Sends a `ping` request to the connected client. + * + * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. + * If your factory serves both eras, this only works on the legacy path. + */ + async ping() { + this._assertPushApiInServedEra("ping"); + return this.request({ method: "ping" }); + } + async createMessage(params, options) { + this._assertPushApiInServedEra("sampling/createMessage"); + if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); + if (params.messages.length > 0) { + const lastMessage = params.messages.at(-1); + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); + if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + const hasTools = Boolean(params.tools || params.toolChoice); + const wide = await this.request({ + method: "sampling/createMessage", + params + }, options); + const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); + if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); + return outcome.value; + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + * + * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) + * instead. The 2025 push-style server-to-client request model is replaced by input_required + * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the + * legacy path. + */ + async elicitInput(params, options) { + this._assertPushApiInServedEra("elicitation/create"); + switch (params.mode ?? "form") { + case "url": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); + break; + case "form": + if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); + break; + } + return this._sendElicitationLeg(params, options); + } + /** + * The capability-check-free core of {@linkcode elicitInput}. The shim + * uses it because its gate differs from the public checks: a bare + * `elicitation: {}` counts as form support (the pre-mode rule), and + * accepted content passes through unvalidated for parity with the + * modern client driver (handlers validate via the schema-aware + * `acceptedContent` overload and can re-ask). + */ + async _sendElicitationLeg(params, options, behavior) { + const mode = params.mode ?? "form"; + const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; + switch (mode) { + case "url": { + const urlParams = params; + return this.request({ + method: "elicitation/create", + params: urlParams + }, options); + } + case "form": { + const formParams = params.mode === "form" ? params : { + ...params, + mode: "form" + }; + const result = await this.request({ + method: "elicitation/create", + params: formParams + }, options); + if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { + const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); + if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * The notification (and the `elicitationId` it references) exists only on protocol revision + * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the + * returned callback rejects with a typed local error before anything reaches the transport + * (the method is not part of that revision's wire registry). + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { elicitationId } + }, options); + } + /** + * Requests the list of roots from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, + * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 + * push-style server-to-client request model is replaced by input_required results in the + * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. + */ + async listRoots(params, options) { + this._assertPushApiInServedEra("roots/list"); + return this.request({ + method: "roots/list", + params + }, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ + method: "notifications/message", + params + }); + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + async sendResourceListChanged() { + return this.notification({ method: "notifications/resources/list_changed" }); + } + async sendToolListChanged() { + return this.notification({ method: "notifications/tools/list_changed" }); + } + async sendPromptListChanged() { + return this.notification({ method: "notifications/prompts/list_changed" }); + } +}; +/** +* The capability set a server advertises on `server/discover`. Pure — never +* mutates the input; the legacy `initialize` advertisement is untouched. +* +* The serving entries serve `subscriptions/listen` themselves, so the +* `listChanged` and `resources.subscribe` capability bits are advertised +* as-is: a modern-era client uses them to decide which notification types to +* request on its listen filter. +*/ +function discoverAdvertisedCapabilities(capabilities) { + return { ...capabilities }; +} + +//#endregion +//#region src/server/mcp.ts +/** +* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. +* For advanced usage (like sending notifications or setting custom request handlers), use the underlying +* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. +* +* @example +* ```ts source="./mcp.examples.ts#McpServer_basicUsage" +* const server = new McpServer({ +* name: 'my-server', +* version: '1.0.0' +* }); +* ``` +*/ +var mcp_DXXb3Vv3_McpServer = class { + /** + * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. + */ + server; + _registeredResources = {}; + _registeredResourceTemplates = {}; + _registeredTools = {}; + _registeredPrompts = {}; + /** + * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 + * registration-time scan and the pre-dispatch validation step share one + * conversion instead of paying it twice per request under the + * per-request-factory `createMcpHandler` model. + */ + _toolInputSchemaJson = {}; + /** + * The JSON-serialized `inputSchema` of a registered tool, or `undefined` + * when no such tool is registered. Used by the HTTP entry's pre-dispatch + * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema + * `tools/list` would emit, before dispatch reaches the handler). + * + * @internal + */ + toolInputSchemaJson(name) { + const tool = this._registeredTools[name]; + if (tool === void 0 || !tool.enabled) return void 0; + if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; + if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; + try { + const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + return json; + } catch { + return; + } + } + constructor(serverInfo, options) { + this.server = new Server(serverInfo, options); + if (options?.capabilities?.tools) this.setToolRequestHandlers(); + if (options?.capabilities?.resources) this.setResourceRequestHandlers(); + if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" + * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); + * const transport = new StdioServerTransport(); + * await server.connect(transport); + * ``` + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + _toolHandlersInitialized = false; + setToolRequestHandlers() { + if (this._toolHandlersInitialized) return; + this.server.assertCanSetRequestHandler("tools/list"); + this.server.assertCanSetRequestHandler("tools/call"); + this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); + this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, + annotations: tool.annotations, + icons: tool.icons, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); + return toolDefinition; + }) })); + this.server.setRequestHandler("tools/call", async (request, ctx) => { + const tool = this._registeredTools[request.params.name]; + if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + try { + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, ctx); + await this.validateToolOutput(tool, result, request.params.name); + if (isInputRequiredResult(result)) return result; + return this.server.projectCallToolResult(result, tool.outputSchemaJson); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [{ + type: "text", + text: errorMessage + }], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) return; + const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) return; + if (isInputRequiredResult(result)) return; + if (result.isError) return; + if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); + } + /** + * Executes a tool handler. + */ + async executeToolHandler(tool, args, ctx) { + return tool.executor(args, ctx); + } + _completionHandlerInitialized = false; + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) return; + this.server.assertCanSetRequestHandler("completion/complete"); + this.server.registerCapabilities({ completions: {} }); + this.server.setRequestHandler("completion/complete", async (request) => { + switch (request.params.ref.type) { + case "ref/prompt": + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case "ref/resource": + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; + const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); + if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; + const completer = getCompleter(field); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + _resourceHandlersInitialized = false; + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) return; + this.server.assertCanSetRequestHandler("resources/list"); + this.server.assertCanSetRequestHandler("resources/templates/list"); + this.server.assertCanSetRequestHandler("resources/read"); + this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); + this.server.setRequestHandler("resources/list", async (_request, ctx) => { + const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) continue; + const result = await template.resourceTemplate.listCallback(ctx); + for (const resource of result.resources) templateResources.push({ + ...template.metadata, + ...resource + }); + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler("resources/templates/list", async () => { + return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })) }; + }); + this.server.setRequestHandler("resources/read", async (request, ctx) => { + let uri; + try { + uri = new URL(request.params.uri); + } catch { + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { + uri: request.params.uri, + reason: "invalid_uri" + }); + } + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); + return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); + } + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); + } + throw new ResourceNotFoundError(request.params.uri); + }); + this._resourceHandlersInitialized = true; + } + _promptHandlersInitialized = false; + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) return; + this.server.assertCanSetRequestHandler("prompts/list"); + this.server.assertCanSetRequestHandler("prompts/get"); + this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); + this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, + icons: prompt.icons, + _meta: prompt._meta + }; + }) })); + this.server.setRequestHandler("prompts/get", async (request, ctx) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + return prompt.handler(request.params.arguments, ctx); + }); + this._promptHandlersInitialized = true; + } + registerResource(name, uriOrTemplate, config, readCallback) { + const cacheHint = config.cacheHint; + let metadata = config; + if (cacheHint !== void 0) { + assertValidCacheHint(cacheHint, `resource ${name}`); + const rest = { ...config }; + delete rest.cacheHint; + metadata = rest; + } + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: (updates) => { + if (updates.uri !== void 0 && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) this._registeredResources[updates.uri] = registeredResource; + } + if (updates.name !== void 0) registeredResource.name = updates.name; + if (updates.title !== void 0) registeredResource.title = updates.title; + if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; + if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; + if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + const variableNames = template.uriTemplate.variableNames; + if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { + let currentArgsSchema = argsSchema; + let currentCallback = callback; + const registeredPrompt = { + title, + description, + argsSchema, + icons, + _meta, + handler: createPromptHandler(name, argsSchema, callback), + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; + } + if (updates.title !== void 0) registeredPrompt.title = updates.title; + if (updates.description !== void 0) registeredPrompt.description = updates.description; + if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; + if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; + let needsHandlerRegen = false; + if (updates.argsSchema !== void 0) { + registeredPrompt.argsSchema = updates.argsSchema; + currentArgsSchema = updates.argsSchema; + needsHandlerRegen = true; + } + if (updates.callback !== void 0) { + currentCallback = updates.callback; + needsHandlerRegen = true; + } + if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); + if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + if (argsSchema) { + const shape = getSchemaShape(argsSchema); + if (shape) { + if (Object.values(shape).some((field) => { + return isCompletable(unwrapOptionalSchema(field)); + })) this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { + validateAndWarnToolName(name); + if (inputSchema !== void 0) try { + const json = standardSchemaToJsonSchema(inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); + if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); + } catch {} + let currentHandler = handler; + const registeredTool = { + title, + description, + inputSchema, + outputSchema, + outputSchemaJson: convertOutputSchemaJson(outputSchema), + annotations, + icons, + execution, + _meta, + handler, + executor: createToolExecutor(inputSchema, handler), + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + if (typeof updates.name === "string") validateAndWarnToolName(updates.name); + delete this._registeredTools[name]; + delete this._toolInputSchemaJson[name]; + if (updates.name) { + delete this._toolInputSchemaJson[updates.name]; + this._registeredTools[updates.name] = registeredTool; + name = updates.name; + } + } + if (updates.title !== void 0) registeredTool.title = updates.title; + if (updates.description !== void 0) registeredTool.description = updates.description; + let needsExecutorRegen = false; + if (updates.paramsSchema !== void 0) { + registeredTool.inputSchema = updates.paramsSchema; + delete this._toolInputSchemaJson[name]; + needsExecutorRegen = true; + } + if (updates.callback !== void 0) { + registeredTool.handler = updates.callback; + currentHandler = updates.callback; + needsExecutorRegen = true; + } + if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); + if (updates.outputSchema !== void 0) { + registeredTool.outputSchema = updates.outputSchema; + registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); + } + if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; + if (updates.icons !== void 0) registeredTool.icons = updates.icons; + if (updates._meta !== void 0) registeredTool._meta = updates._meta; + if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + registerTool(name, config, cb) { + if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); + const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; + return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); + } + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); + const { title, description, argsSchema, icons, _meta } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns `true` if the server is connected + */ + isConnected() { + return this.server.transport !== void 0; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" + * await server.sendLoggingMessage({ + * level: 'info', + * data: 'Processing complete' + * }); + * ``` + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) this.server.sendResourceListChanged(); + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) this.server.sendToolListChanged(); + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) this.server.sendPromptListChanged(); + } +}; +/** +* A resource template combines a URI pattern with optional functionality to enumerate +* all resources matching that pattern. +*/ +var ResourceTemplate = class { + _uriTemplate; + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +}; +/** +* Creates an executor that invokes the handler with the appropriate arguments. +* When `inputSchema` is defined, the handler is called with `(args, ctx)`. +* When `inputSchema` is undefined, the handler is called with just `(ctx)`. +*/ +function createToolExecutor(inputSchema, handler) { + if (inputSchema) { + const callback$1 = handler; + return async (args, ctx) => callback$1(args, ctx); + } + const callback = handler; + return async (_args, ctx) => callback(ctx); +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {} +}; +/** +* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} +* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that +* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion +* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). +*/ +function convertOutputSchemaJson(outputSchema) { + if (outputSchema === void 0) return void 0; + try { + return standardSchemaToJsonSchema(outputSchema, "output"); + } catch { + return; + } +} +/** +* Creates a type-safe prompt handler that captures the schema and callback in a closure. +* This eliminates the need for type assertions at the call site. +*/ +function createPromptHandler(name, argsSchema, callback) { + if (argsSchema) { + const typedCallback = callback; + return async (args, ctx) => { + const parseResult = await validateStandardSchema(argsSchema, args); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); + return typedCallback(parseResult.data, ctx); + }; + } else { + const typedCallback = callback; + return async (_args, ctx) => { + return typedCallback(ctx); + }; + } +} +function createCompletionResult(suggestions) { + return { completion: { + values: suggestions.map(String).slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } }; +} +const EMPTY_COMPLETION_RESULT = { completion: { + values: [], + hasMore: false +} }; +/** @internal Gets the shape of a Zod object schema */ +function getSchemaShape(schema) { + const candidate = schema; + if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; +} +/** @internal Checks if a Zod schema is optional */ +function isOptionalSchema(schema) { + return schema?.type === "optional"; +} +/** @internal Unwraps an optional Zod schema */ +function unwrapOptionalSchema(schema) { + if (!isOptionalSchema(schema)) return schema; + return schema.def?.innerType ?? schema; +} + +//#endregion + +//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map + + + + +//#region src/server/perRequestTransport.ts +/** +* The per-request micro-transport: a real, connected `Transport` whose whole +* lifetime is one HTTP exchange. See the module documentation for the +* response shapes it produces. +*/ +var PerRequestHTTPServerTransport = class { + onclose; + onerror; + onmessage; + _classification; + _responseMode; + _started = false; + _used = false; + _closed = false; + _terminalDelivered = false; + /** + * `true` only while the inbound message is being delivered synchronously + * to the connected protocol layer. The pre-handler gates (the era + * registry gate, the edge→instance handoff check, the missing-handler + * rejection) answer inside this window; request handlers always run + * after it (the protocol layer defers them to a microtask). An error + * sent inside the window is therefore ladder-originated, and an error + * sent after it is handler-produced. + */ + _dispatchWindowOpen = false; + _requestId; + _deferredResponse; + _sse; + _abortCleanup; + _keepAliveMs; + constructor(options) { + this._classification = options.classification; + this._responseMode = options.responseMode ?? "auto"; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + async start() { + if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); + this._started = true; + } + /** + * Serves the single exchange: delivers the classified message to the + * connected server instance and resolves with the HTTP response. + * + * Throws when called a second time (the transport is strictly + * single-use), or before a server has been connected to the transport. + * The returned promise rejects with a connection-closed error when the + * transport is closed before a response was produced (for example because + * the client disconnected). + */ + async handleMessage(message, extra) { + if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); + if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); + if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); + this._used = true; + const signal = extra?.request?.signal; + if (signal?.aborted) { + await this.close(); + throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); + } + const messageExtra = { + classification: this._classification, + ...extra?.request !== void 0 && { request: extra.request }, + ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } + }; + if (isJSONRPCRequest(message)) { + this._requestId = message.id; + let resolve; + let reject; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + this._deferredResponse = { + promise, + resolve, + reject, + settled: false + }; + if (signal !== void 0) { + const onAbort = () => void this.close(); + signal.addEventListener("abort", onAbort, { once: true }); + this._abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + this._dispatchWindowOpen = true; + try { + this.onmessage(message, messageExtra); + } finally { + this._dispatchWindowOpen = false; + } + if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); + return promise; + } + this.onmessage(message, messageExtra); + return new Response(null, { status: 202 }); + } + async send(message, options) { + if (this._closed) return; + const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); + const relatedId = isResponse ? message.id : options?.relatedRequestId; + if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { + if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); + return; + } + if (isResponse) { + if (this._terminalDelivered) return; + this._terminalDelivered = true; + const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; + const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; + if (ladderStatus !== void 0 && this._sse === void 0) { + this.settleResponse(Response.json(message, { + status: ladderStatus, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._sse !== void 0 || this._responseMode === "sse") { + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + this.finalizeStream(); + return; + } + this.settleResponse(Response.json(message, { + status: 200, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._responseMode === "json") return; + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + } + /** + * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the + * exchange is not currently streaming. + */ + writeCommentFrame(comment) { + if (this._closed || this._sse === void 0 || this._sse.closed) return; + const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); + this.writeFrame(`${frame}\n\n`); + } + async close() { + if (this._closed) return; + this._closed = true; + this._abortCleanup?.(); + this._abortCleanup = void 0; + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { + this._deferredResponse.settled = true; + this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); + } + this.onclose?.(); + } + settleResponse(response) { + if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; + this._deferredResponse.settled = true; + this._deferredResponse.resolve(response); + } + upgradeToSse() { + let controller; + const readable = new ReadableStream({ + start: (streamController) => { + controller = streamController; + }, + cancel: () => { + this.close(); + } + }); + this._sse = { + controller, + encoder: new TextEncoder(), + closed: false + }; + this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); + this.settleResponse(new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + })); + } + finalizeStream() { + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + queueMicrotask(() => void this.close()); + } + writeMessageFrame(message) { + this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + writeFrame(frame) { + if (this._sse === void 0 || this._sse.closed) return; + try { + this._sse.controller.enqueue(this._sse.encoder.encode(frame)); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); + } + } +}; + +//#endregion +//#region src/server/invoke.ts +/** +* Serves one classified inbound message on the given server instance and +* returns the HTTP response for the exchange. +* +* The instance is connected to a fresh single-exchange transport, the message +* is injected through the normal transport message path, and whatever the +* dispatch layer produces (the handler result, a protocol-level rejection, or +* streamed related messages followed by the result) is captured as the +* returned `Response`. For request exchanges, teardown rides the transport's +* close chain once the terminal response has been delivered; notification +* exchanges resolve with the 202 response immediately and do NOT run the +* close chain — the transport stays connected until the caller closes it or +* drops the per-request instance, which is the caller's choice either way. +*/ +async function invoke(server, message, ctx) { + const transport = new PerRequestHTTPServerTransport({ + classification: ctx.classification, + ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, + ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } + }); + await server.connect(transport); + return transport.handleMessage(message, { + ...ctx.request !== void 0 && { request: ctx.request }, + ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } + }); +} + +//#endregion +//#region src/server/streamableHttp.ts +/** +* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification +* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). +* +* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. +* +* In stateful mode: +* - Session ID is generated and included in response headers +* - Session ID is always included in initialization responses +* - Requests with invalid session IDs are rejected with `404 Not Found` +* - Non-initialization requests without a session ID are rejected with `400 Bad Request` +* - State is maintained in-memory (connections, message history) +* +* In stateless mode: +* - No Session ID is included in any responses +* - No session validation is performed +* +* @example Stateful setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: () => crypto.randomUUID() +* }); +* +* await server.connect(transport); +* ``` +* +* @example Stateless setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: undefined +* }); +* ``` +* +* @example Hono.js +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" +* app.all('/mcp', async c => { +* return transport.handleRequest(c.req.raw); +* }); +* ``` +* +* @example Cloudflare Workers +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" +* const worker = { +* async fetch(request: Request): Promise { +* return transport.handleRequest(request); +* } +* }; +* ``` +*/ +var WebStandardStreamableHTTPServerTransport = class { + sessionIdGenerator; + _started = false; + _closed = false; + _streamMapping = /* @__PURE__ */ new Map(); + _requestToStreamMapping = /* @__PURE__ */ new Map(); + _requestResponseMap = /* @__PURE__ */ new Map(); + _initialized = false; + _enableJsonResponse = false; + _standaloneSseStreamId = "_GET_stream"; + _eventStore; + _onsessioninitialized; + _onsessionclosed; + _allowedHosts; + _allowedOrigins; + _enableDnsRebindingProtection; + _retryInterval; + _supportedProtocolVersions; + _keepAliveMs; + sessionId; + onclose; + onerror; + onmessage; + constructor(options = {}) { + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + startKeepAlive(controller, encoder) { + if (this._closed) return void 0; + const timer = armSseKeepAlive(this._keepAliveMs, () => { + try { + controller.enqueue(encoder.encode(": keepalive\n\n")); + } catch { + if (timer !== void 0) clearInterval(timer); + } + }); + return timer; + } + /** + * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) throw new Error("Transport already started"); + this._started = true; + } + /** + * Sets the supported protocol versions for header validation. + * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. + */ + setSupportedProtocolVersions(versions) { + this._supportedProtocolVersions = versions; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { + code, + message + }; + if (options?.data !== void 0) error.data = options.data; + return Response.json({ + jsonrpc: "2.0", + error, + id: null + }, { + status, + headers: { + "Content-Type": "application/json", + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, `undefined` if validation passes. + */ + validateRequestHeaders(req) { + if (!this._enableDnsRebindingProtection) return; + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get("host"); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get("origin"); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + } + /** + * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` + * Returns a `Response` object (Web Standard) + */ + async handleRequest(req, options) { + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const validationError = this.validateRequestHeaders(req); + if (validationError) return validationError; + switch (req.method) { + case "POST": return this.handlePostRequest(req, options); + case "GET": return this.handleGetRequest(req); + case "DELETE": return this.handleDeleteRequest(req); + default: return this.handleUnsupportedRequest(); + } + } + /** + * Returns true if the client's protocol version supports empty SSE data in + * priming events (the fix shipped with protocol version `2025-11-25`). + * + * The version is checked for membership in this transport instance's + * supported protocol versions rather than with an open-ended + * `>= '2025-11-25'` comparison: the value may come from an `initialize` + * request body, which (unlike the `MCP-Protocol-Version` header) is not + * validated against `supportedProtocolVersions` before reaching this + * check. An unknown future version string must not silently enable + * behavior reserved for versions this transport actually supports. + */ + supportsEmptySSEData(protocolVersion) { + return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if `eventStore` is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (a supported + * version that is >= `2025-11-25`). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) return; + if (!this.supportsEmptySSEData(protocolVersion)) return; + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles `GET` requests for SSE stream + */ + async handleGetRequest(req) { + if (!req.headers.get("accept")?.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); + } + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + if (this._eventStore) { + const lastEventId = req.headers.get("last-event-id"); + if (lastEventId) return this.replayEvents(lastEventId); + } + if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); + } + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } catch {} + } + }); + keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); + return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); + } + try { + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); + return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); + } + if (this._streamMapping.get(streamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); + } + } + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + let cancelled = false; + let replayedStreamId; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + cancelled = true; + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); + } + }); + const replayedEventIds = /* @__PURE__ */ new Set(); + replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { + replayedEventIds.add(eventId); + if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { + streamController.close(); + } catch {} + } }); + if (this._closed || cancelled) { + try { + streamController.close(); + } catch {} + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + this._streamMapping.get(replayedStreamId)?.cleanup(); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + replayedEventIds, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + }); + if (replayedStreamId !== this._standaloneSseStreamId) { + if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + } + if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + if (eventId) eventData += `id: ${eventId}\n`; + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } catch (error) { + this.onerror?.(error); + return false; + } + } + /** + * Handles unsupported requests (`PUT`, `PATCH`, etc.) + */ + handleUnsupportedRequest() { + this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: "Method not allowed." + }, + id: null + }, { + status: 405, + headers: { + Allow: "GET, POST, DELETE", + "Content-Type": "application/json" + } + }); + } + /** + * Handles `POST` requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + const acceptHeader = req.headers.get("accept"); + if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); + } + if (!isJsonContentType(req.headers.get("content-type"))) { + this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const request = req; + let rawMessage; + if (options?.parsedBody === void 0) try { + rawMessage = await req.json(); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); + } + else rawMessage = options.parsedBody; + let messages; + try { + messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); + if (isInitializationRequest) { + if (this._initialized && this.sessionId !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); + } + if (messages.length > 1) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + if (!isInitializationRequest) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + if (!messages.some((element) => isJSONRPCRequest(element))) { + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + return new Response(null, { status: 202 }); + } + const streamId = crypto.randomUUID(); + const initRequest = messages.find((m) => isInitializeRequest(m)); + const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (this._enableJsonResponse) return new Promise((resolve) => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + }); + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + for (const message of messages) if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(streamId); + try { + streamController.close(); + } catch {} + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + for (const message of messages) { + let closeSSEStream; + let closeStandaloneSSEStream; + if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { + authInfo: options?.authInfo, + request, + closeSSEStream, + closeStandaloneSSEStream + }); + } + if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { + status: 200, + headers + }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); + } + } + /** + * Handles `DELETE` requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + try { + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + return new Response(null, { status: 200 }); + } finally { + await this.close(); + } + } + /** + * Validates session ID for non-initialization requests. + * Returns `Response` error if invalid, `undefined` otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === void 0) return; + if (!this._initialized) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); + } + const sessionId = req.headers.get("mcp-session-id"); + if (!sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); + } + if (sessionId !== this.sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Session not found")); + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + } + /** + * Validates the `MCP-Protocol-Version` header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with `MCP-Protocol-Version` header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the `MCP-Protocol-Version` header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get("mcp-protocol-version"); + if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { + const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(400, -32e3, error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + for (const { cleanup } of this._streamMapping.values()) cleanup(); + this._streamMapping.clear(); + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) return; + const stream = this._streamMapping.get(streamId); + if (stream) stream.cleanup(); + } + /** + * Close the standalone `GET` SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) stream.cleanup(); + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; + if (requestId === void 0) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); + let eventId; + if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === void 0) return; + if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + return; + } + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); + let stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse) { + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + stream = this._streamMapping.get(streamId); + } + if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); + if (relatedIds.every((id) => this._requestResponseMap.has(id))) { + if (!stream) { + if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + if (this._enableJsonResponse && stream.resolveJson) { + const headers = { "Content-Type": "application/json" }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); + if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { + status: 200, + headers + })); + else stream.resolveJson(Response.json(responses, { + status: 200, + headers + })); + stream.cleanup(); + } else stream.cleanup(); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +}; + +//#endregion +//#region src/server/createMcpHandler.ts +/** +* The JSON-RPC id to echo on an entry-built error response: the body's `id` +* when the body is a single JSON-RPC request whose id is a string or number, +* `null` otherwise. Error responses must carry the id of the request they +* correspond to whenever it could be read; `null` is reserved for the cases +* where no single request id is determinable — unparseable bodies, body-less +* methods, notifications, posted responses and batch arrays. +*/ +function echoableRequestId(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) return null; + const { method, id } = body; + if (typeof method !== "string") return null; + return typeof id === "string" || typeof id === "number" ? id : null; +} +function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message, + ...data !== void 0 && { data } + }, + id + }, { status: httpStatus }); +} +function rejectionResponse(rejection, id = null) { + return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); +} +function toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} +function internalServerErrorResponse(id = null) { + return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); +} +/** +* The entry's default legacy serving (`legacy: 'stateless'`): per-request +* stateless serving of 2025-era traffic using the same factory as the modern +* path. Exported as a standalone building block for hand-wired compositions +* (for example mounting legacy stateless serving on its own route next to a +* strict modern endpoint). +* +* Each POST is served by a fresh instance from the factory connected to a +* fresh streamable HTTP transport constructed with only +* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. +* Because serving is per-request and stateless, GET and DELETE (2025 session +* operations) are answered with `405` / `Method not allowed.`, exactly like the +* canonical stateless example. +* +* The optional `onerror` callback receives factory and serving failures on +* this leg (reporting only — the response stays the 500 internal-error body). +* The entry passes its own `onerror` here when expanding the default, so +* legacy-leg failures are never silently swallowed. +*/ +function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { + return async (request, options) => { + if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); + try { + const product = await factory({ + era: "legacy", + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + requestInfo: request + }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: void 0, + ...keepAliveMs !== void 0 && { keepAliveMs } + }); + await product.connect(transport); + const teardown = () => { + transport.close().catch(() => {}); + product.close().catch(() => {}); + }; + request.signal?.addEventListener("abort", teardown, { once: true }); + const response = await transport.handleRequest(request, { + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } + }); + if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { + teardown(); + return response; + } + const reader = response.body.getReader(); + let toreDown = false; + const completeExchange = () => { + if (!toreDown) { + toreDown = true; + teardown(); + } + }; + const monitoredBody = new ReadableStream({ + pull: async (controller) => { + try { + const { done, value } = await reader.read(); + if (done) { + completeExchange(); + controller.close(); + return; + } + if (value !== void 0) controller.enqueue(value); + } catch (error) { + completeExchange(); + controller.error(error); + } + }, + cancel: (reason) => { + completeExchange(); + return reader.cancel(reason).catch(() => {}); + } + }); + return new Response(monitoredBody, { + status: response.status, + statusText: response.statusText, + headers: response.headers + }); + } catch (error) { + try { + onerror?.(toError(error)); + } catch {} + return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); + } + }; +} +function legacyStatelessFallback(factory, onerror) { + return createLegacyStatelessFallback(factory, onerror); +} +/** +* The entry's classification step: read the request body exactly once (unless +* a pre-parsed body is supplied) and classify the request with +* {@linkcode classifyInboundRequest}. This is the single code path behind both +* {@linkcode createMcpHandler}'s routing and the exported +* {@linkcode isLegacyRequest} predicate, so the two can never disagree. +* +* Pass `needsForward: false` when the caller never reads `forwardRequest` — +* the body-preserving clone is then skipped and `forwardRequest` is the +* (consumed) input request. +*/ +async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { + const httpMethod = request.method.toUpperCase(); + let body; + let parsedBody = providedParsedBody; + let forwardRequest = request; + let unparseable = false; + if (httpMethod === "POST") { + if (parsedBody === void 0) { + if (needsForward) forwardRequest = request.clone(); + let bodyText; + try { + bodyText = await request.text(); + } catch { + return { step: "unreadable-body" }; + } + try { + body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); + } catch { + unparseable = true; + } + if (!unparseable && body !== void 0) parsedBody = body; + } else body = parsedBody; + if (unparseable || body === void 0) return { + step: "no-json-body", + forwardRequest + }; + } + return { + step: "classified", + outcome: classifyInboundRequest({ + httpMethod, + protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0, + ...body !== void 0 && { body } + }), + body, + parsedBody, + forwardRequest + }; +} +/** +* Whether {@linkcode createMcpHandler} would route this request to its legacy +* (2025-era) serving rather than the modern (2026-07-28) path. +* +* Call it with just the request: `await isLegacyRequest(request)`. For a +* `POST` the body is read from an internal clone, so the request you pass +* stays fully readable for whichever handler you route it to — no second +* argument is needed. (In a Node `(req, res)` handler, build that `Request` +* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body +* parser, which has already drained the Node stream, build it as +* `toWebRequest(req, req.body)` so the bytes come from the parsed body — +* either way the predicate still takes just the request.) The optional +* `parsedBody` is a perf escape hatch for a body you already hold parsed: +* pass it and the predicate classifies from the value directly, reading and +* cloning nothing. It is needed, not just faster, when the request's own +* body was already read — the internal clone is then impossible (cloning a +* used body throws a `TypeError`), so such a single-argument call rejects +* instead of guessing. +* +* This is the entry's own classification step exported as a predicate — it +* runs exactly the code `createMcpHandler` runs to make the routing decision, +* not a re-implementation — so a hand-wired composition that branches on it +* can never disagree with the entry. It is classification only: hand-wired +* compositions must validate Content-Type themselves (415 for POSTs whose +* media type is not `application/json`, via {@linkcode isJsonContentType}) +* before dispatching either leg — routing the legacy leg into the SDK +* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy +* deployment (for example a sessionful streamable HTTP wiring) serving 2025 +* traffic next to a strict modern endpoint, now that the entry has no +* handler-valued `legacy` option: +* +* ```ts +* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; +* +* const modern = createMcpHandler(factory, { legacy: 'reject' }); +* +* export default { +* async fetch(request: Request): Promise { +* if (await isLegacyRequest(request)) { +* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring +* return myExistingLegacyHandler(request); +* } +* return modern.fetch(request); +* } +* }; +* ``` +* +* Semantics (identical to the entry's routing): +* +* - Returns `true` only for requests with no per-request `_meta` envelope +* claim: claim-less POSTs (including the `initialize` handshake and 2025-era +* notification POSTs without a modern protocol-version header), body-less +* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted +* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. +* - Returns `false` for everything the modern path answers, including its +* validation-ladder rejections: a request carrying the envelope claim (even +* one naming a revision the endpoint does not serve — the modern path +* answers it with the unsupported-protocol-version error), a malformed +* envelope behind a present claim (answered `-32602`), a request whose +* `MCP-Protocol-Version` header names a modern revision but that lacks the +* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers +* routing on the predicate must send `false` traffic to the modern handler, +* never to a legacy handler — the modern path owns those error answers. +* - `server/discover` probes sent by negotiating clients always carry the +* envelope claim, so they are never legacy; a hand-built claim-less POST to +* a method named `server/discover` has no claim and classifies legacy, +* exactly as the entry itself routes it. +*/ +async function isLegacyRequest(request, parsedBody) { + const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); + return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; +} +/** +* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a +* per-request server factory and, by default, falls back to old-school +* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a +* modern-only strict endpoint. +* +* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, +* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap +* the handler once with `toNodeHandler(handler)` from +* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, +* put Origin/Host validation in front of the handler — the entry itself is +* deliberately validation-free: +* +* ```ts +* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; +* +* export default { +* async fetch(request: Request): Promise { +* const rejected = +* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? +* originValidationResponse(request, localhostAllowedOrigins()); +* return rejected ?? handler.fetch(request); +* } +* }; +* ``` +* +* Use ONE factory for both legs: the same tools/resources/prompts definition +* backs the modern path and the stateless legacy fallback, so the two eras can +* never drift apart. To keep an existing legacy deployment (for example a +* sessionful streamable HTTP wiring) serving 2025 traffic instead of the +* stateless fallback, route in user land with {@linkcode isLegacyRequest} in +* front of a strict handler — see that predicate's documentation for the +* pattern. Power users composing transport-neutral routing can also use the +* exported building blocks directly: {@linkcode classifyInboundRequest} for +* the era decision and `PerRequestHTTPServerTransport` for single-exchange +* serving — such compositions must reject POSTs whose Content-Type media type +* is not `application/json` (415) before parsing the body, using +* {@linkcode isJsonContentType}; neither building block performs this +* validation itself. +* +* The entry performs no token verification: `authInfo` given to `fetch` is +* passed through to handlers and the factory as-is and is never derived from +* request headers. +*/ +function createMcpHandler(factory, options = {}) { + const { legacy, onerror, responseMode } = options; + if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); + /** Modern per-request instances with an exchange still in flight (close() tears these down). */ + const inflight = /* @__PURE__ */ new Set(); + let closed = false; + const reportError = (error) => { + try { + onerror?.(error); + } catch {} + }; + const bus = options.bus ?? new InMemoryServerEventBus(reportError); + const notify = createServerNotifier(bus); + const listenRouter = createListenRouter({ + bus, + maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, + keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, + onerror: reportError + }); + if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); + const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); + async function serveModern(route, request, authInfo) { + const claimedRevision = route.classification.revision; + if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedRevision ?? "unknown" + }); + reportError(error); + return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); + } + const stdHeaderRejection = validateStandardRequestHeaders({ + httpMethod: request.method, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0 + }, route); + if (stdHeaderRejection !== void 0) { + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); + return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); + } + const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; + const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; + if (route.messageKind === "request") { + const required = requiredClientCapabilitiesForRequest(route.message.method); + if (required !== void 0) { + const missing = missingClientCapabilities(required, declaredClientCapabilities); + if (missing !== void 0) { + const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); + reportError(error); + return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); + } + } + } + const product = await factory({ + era: "modern", + ...authInfo !== void 0 && { authInfo }, + requestInfo: request + }); + const server = product instanceof McpServer ? product.server : product; + if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { + const capabilities = server.getCapabilities(); + const serverInfo = serverIdentityOf(server); + product.close().catch(reportError); + return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); + } + if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { + const callParams = route.message.params; + const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; + const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); + if (inputSchema !== void 0) { + const scan = scanXMcpHeaderDeclarations(inputSchema); + if (scan.valid && scan.declarations.length > 0) { + const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); + if (rejection !== void 0) { + product.close().catch(reportError); + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); + return rejectionResponse(rejection, route.message.id); + } + } + } + } + setNegotiatedProtocolVersion(server, claimedRevision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (meta !== void 0) seedClientIdentityFromEnvelope(server, { + clientInfo: meta[CLIENT_INFO_META_KEY], + clientCapabilities: declaredClientCapabilities + }); + const previousOnClose = server.onclose; + inflight.add(server); + server.onclose = () => { + inflight.delete(server); + previousOnClose?.(); + }; + try { + const response = await invoke(product, route.message, { + classification: route.classification, + request, + ...authInfo !== void 0 && { authInfo }, + ...responseMode !== void 0 && { responseMode }, + ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } + }); + if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); + return response; + } catch (error) { + if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); + await server.close().catch(() => {}); + inflight.delete(server); + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(route.message)); + } + } + async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { + if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { + ...authInfo !== void 0 && { authInfo }, + ...parsedBody !== void 0 && { parsedBody } + }); + const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (strict === void 0) return new Response(null, { status: 202 }); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); + return rejectionResponse(strict, echoableRequestId(parsedBody)); + } + async function handle(request, requestOptions) { + const authInfo = requestOptions?.authInfo; + if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { + reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); + if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); + if (classified.step === "no-json-body") { + if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); + return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); + } + const { outcome, body, parsedBody, forwardRequest } = classified; + try { + switch (outcome.kind) { + case "reject": + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); + return rejectionResponse(outcome, echoableRequestId(body)); + case "modern": return await serveModern(outcome, request, authInfo); + case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); + } + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(body)); + } + } + const fetchFace = async (request, requestOptions) => { + if (closed) throw new Error("This MCP handler has been closed"); + try { + return await handle(request, requestOptions); + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); + } + }; + return { + fetch: fetchFace, + notify, + bus, + close: async () => { + closed = true; + listenRouter.closeAll(); + const closing = [...inflight].map((server) => server.close().catch(() => {})); + inflight.clear(); + await Promise.all(closing); + } + }; +} + +//#endregion +//#region src/server/middleware/bearerAuth.ts +function headerQuotedValue(value) { + return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); +} +function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { + let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; + if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; + if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; + return header; +} +/** +* Validate a raw `Authorization` header value as a Bearer token and return +* the verified {@link AuthInfo}. +* +* The runtime-neutral core of Bearer authentication: it parses the header, +* runs the verifier, enforces `requiredScopes`, and rejects tokens without an +* expiration or past it. On any failure it throws an {@link OAuthError} — +* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP +* answer, or use {@link requireBearerAuth} to get both steps as one call. +* +* Framework adapters build on this: `requireBearerAuth` from +* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. +*/ +async function verifyBearerToken(authorizationHeader, options) { + const { verifier, requiredScopes = [] } = options; + if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); + const [type, token] = authorizationHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); + const authInfo = await verifier.verifyAccessToken(token); + if (requiredScopes.length > 0) { + if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); + } + if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); + else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); + return authInfo; +} +/** +* Build the HTTP answer for a Bearer authentication failure. +* +* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and +* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` +* challenge, with `resource_metadata` when configured so clients can discover +* the Authorization Server), `500` for `server_error`, `400` for anything +* else. A non-`OAuthError` value answers `500 server_error`. The body is the +* OAuth error JSON. +*/ +function bearerAuthChallengeResponse(error, options) { + const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; + if (!(error instanceof OAuthError)) { + const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); + return Response.json(serverError.toResponseObject(), { status: 500 }); + } + switch (error.code) { + case OAuthErrorCode.InvalidToken: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 401, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.InsufficientScope: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 403, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); + default: return Response.json(error.toResponseObject(), { status: 400 }); + } +} +/** +* Require a valid Bearer token on web-standard requests. +* +* The framework-free counterpart of `requireBearerAuth` from +* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a +* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The +* returned gate resolves to the verified {@link AuthInfo}, or to the +* ready-to-return challenge `Response` when the request must be refused. +* +* @example +* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" +* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); +* +* async function fetchHandler(request: Request): Promise { +* const auth: AuthInfo | Response = await gate(request); +* if (auth instanceof Response) return auth; +* return handler.fetch(request, { authInfo: auth }); +* } +* ``` +*/ +function requireBearerAuth(options) { + const { verifier, requiredScopes = [], resourceMetadataUrl } = options; + const resolved = { + verifier, + requiredScopes, + resourceMetadataUrl + }; + return async (request) => { + const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); + try { + return await verifyBearerToken(authorizationHeader || void 0, resolved); + } catch (error) { + return bearerAuthChallengeResponse(error, resolved); + } + }; +} + +//#endregion +//#region src/server/middleware/hostHeaderValidation.ts +/** +* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). +* +* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). +* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). +*/ +function validateHostHeader(hostHeader, allowedHostnames) { + if (!hostHeader) return { + ok: false, + errorCode: "missing_host", + message: "Missing Host header" + }; + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_host_header", + message: `Invalid Host header: ${hostHeader}`, + hostHeader + }; + } + if (!allowedHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_host", + message: `Invalid Host: ${hostname}`, + hostHeader, + hostname + }; + return { + ok: true, + hostname + }; +} +/** +* Convenience allowlist for `localhost` DNS rebinding protection. +*/ +function localhostAllowedHostnames() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for DNS rebinding protection. +* @example +* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" +* const result = validateHostHeader(req.headers.get('host'), ['localhost']); +* ``` +*/ +function hostHeaderValidationResponse(req, allowedHostnames) { + const result = validateHostHeader(req.headers.get("host"), allowedHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/middleware/oauthMetadata.ts +function checkIssuerUrl(issuer, allowInsecure) { + if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); + if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); +} +/** +* Derive the RFC 9728 Protected Resource Metadata document from +* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL +* (HTTPS required outside localhost) in the process. +* +* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build +* on this; use it directly when serving the document through your own +* routing — or call it once at startup to fail fast on a misconfigured +* issuer before any request arrives. +*/ +function buildOAuthProtectedResourceMetadata(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); + return { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; +} +/** +* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server +* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. +* +* @example +* ```ts +* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) +* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' +* ``` +*/ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; +} +/** The RFC 9728 path-aware well-known path for a resource URL. */ +function protectedResourceMetadataPath(resourceServerUrl) { + const rsPath = stripTrailingSlash(resourceServerUrl.pathname); + return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; +} +function stripTrailingSlash(path) { + return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; +} +const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; +function metadataDocumentResponse(request, metadata) { + if (request.method === "OPTIONS") { + const requestedHeaders = request.headers.get("access-control-request-headers"); + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": ALLOWED_METHODS, + ...requestedHeaders === null ? {} : { + "Access-Control-Allow-Headers": requestedHeaders, + Vary: "Access-Control-Request-Headers" + } + } + }); + } + if (request.method !== "GET" && request.method !== "HEAD") { + const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); + return Response.json(error.toResponseObject(), { + status: 405, + headers: { + Allow: ALLOWED_METHODS, + "Access-Control-Allow-Origin": "*" + } + }); + } + const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); + return request.method === "HEAD" ? new Response(null, { + status: response.status, + headers: response.headers + }) : response; +} +/** +* Serve the two OAuth discovery documents an MCP server acting as a Resource +* Server exposes, from a web-standard `fetch(request)` handler: +* +* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected +* Resource Metadata, derived from the supplied options (path-aware: the +* resource URL's path is reflected in the route). +* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization +* Server Metadata, passed through verbatim. +* +* Returns the matched document `Response` (JSON with permissive CORS, `405` +* with an `Allow` header for non-GET methods, `204` for CORS preflight), or +* `undefined` when the request path is neither well-known route — fall +* through to your own routing. The framework-free counterpart of +* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with +* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so +* unauthenticated clients can discover the AS from the `401` challenge. +* +* @example +* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" +* async function fetchHandler(request: Request): Promise { +* return oauthMetadataResponse(request, options) ?? serveMcp(request); +* } +* ``` +*/ +function oauthMetadataResponse(request, options) { + const requestPath = stripTrailingSlash(new URL(request.url).pathname); + if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); + if (requestPath === "/.well-known/oauth-authorization-server") { + buildOAuthProtectedResourceMetadata(options); + return metadataDocumentResponse(request, options.oauthMetadata); + } +} + +//#endregion +//#region src/server/middleware/originValidation.ts +/** +* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). +* +* - A missing/empty `Origin` header passes: non-browser clients do not send one, +* and only browser-originated requests carry the header this check defends against. +* - Allowlist items are hostnames only (no scheme, no port), the same convention as +* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). +* - Any present value that cannot be parsed as an origin URL — including the literal +* `null` origin browsers send for opaque contexts — is rejected (deny on failure). +*/ +function validateOriginHeader(originHeader, allowedOriginHostnames) { + if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; + let hostname; + try { + hostname = new URL(originHeader).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + } + if (hostname === "") return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + if (!allowedOriginHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_origin", + message: `Invalid Origin: ${hostname}`, + originHeader, + hostname + }; + return { + ok: true, + origin: originHeader, + hostname + }; +} +/** +* Convenience allowlist of localhost-class origin hostnames, mirroring +* `localhostAllowedHostnames`. +*/ +function localhostAllowedOrigins() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC +* error response when the request's `Origin` header is not allowed, and +* `undefined` when the request may proceed. +* +* ```ts +* const rejected = originValidationResponse(request, localhostAllowedOrigins()); +* if (rejected) return rejected; +* ``` +*/ +function originValidationResponse(req, allowedOriginHostnames) { + const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/requestStateCodec.ts +const PREFIX = "v1."; +function bytesToBase64Url(bytes) { + let bin = ""; + for (const b of bytes) bin += String.fromCodePoint(b); + return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} +function constantTimeTagEqual(a, b) { + if (a.length !== b.length) return false; + let r = 0; + for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); + return r === 0; +} +function base64UrlToBytes(s) { + const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return bytes; +} +/** +* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` +* (protocol revision 2026-07-28). +* +* `requestState` round-trips through the client and is attacker-controlled +* input on re-entry. The SDK applies no protection of its own; this helper is +* the convenience implementation of the spec's integrity MUST so authors don't +* hand-roll HMAC. Wire shape: +* +* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) +* +* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` +* — the binding value is never embedded raw. +* +* The codec is **signed, not encrypted**: the body is integrity-protected but +* the client can base64url-decode it and read the payload (`p`) in clear. Do +* not put secrets in the payload; use an AEAD construction if confidentiality +* is required. The handler reads its payload back via the typed +* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` +* (integrity proven, payload decoded) by the time the handler is entered. +* +* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for +* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). +* See `examples/mrtr/server.ts` for a worked end-to-end example. +* +* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference +* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and +* derives independent cipher / bind-HMAC sub-keys from the operator secret via +* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is +* supplied. This codec deliberately ships only the signed mode and a single +* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and +* an encrypted mode are intentionally out of scope for the initial release. +*/ +function createRequestStateCodec(options) { + const subtle = globalThis.crypto?.subtle; + if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); + const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); + if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); + const ttlSeconds = options.ttlSeconds ?? 600; + if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); + const bind = options.bind; + let cryptoKey; + const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { + name: "HMAC", + hash: "SHA-256" + }, false, ["sign", "verify"]); + const utf8 = new TextEncoder(); + const BIND_LABEL = "mcp.requestState.bind:"; + const bindTag = async (value) => { + return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); + }; + return { + async mint(payload, ctx) { + const envelope = { + p: payload, + exp: Math.floor(Date.now() / 1e3) + ttlSeconds + }; + if (bind !== void 0) { + if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); + envelope.b = await bindTag(bind(ctx)); + } + const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); + return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; + }, + async verify(state, ctx) { + const dot = state.lastIndexOf("."); + if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); + const body = state.slice(3, dot); + let macBytes; + try { + macBytes = base64UrlToBytes(state.slice(dot + 1)); + } catch { + throw new Error("malformed"); + } + if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); + let envelope; + try { + envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); + } catch { + throw new Error("malformed"); + } + if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); + if (bind !== void 0) { + const expected = await bindTag(bind(ctx)); + if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); + } else if (envelope.b !== void 0) throw new Error("bind"); + return envelope.p; + } + }; +} + +//#endregion +//#region src/fromJsonSchema.ts +let _defaultValidator; +function dist_fromJsonSchema(schema, validator) { + return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); +} + +//#endregion + +//# sourceMappingURL=index.mjs.map +const mcpApps = Object.freeze([]); + +/* export default */ const mcp_status_073c1634_0 = (mcpApps); + +// Generated by agent-bundle. Do not edit. +const meta_name = "mcp-app-example"; +const packageName = "@agent-bundle-example/mcp-app"; +const packageVersion = undefined; +const meta_version = "1.0.0"; +const meta_meta = Object.freeze({ + name: meta_name, + packageName: packageName, + packageVersion: packageVersion, + version: meta_version +}); +/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + + + + +const app = mcp_status_073c1634_0["0"]; +if (app === undefined) throw new Error('Expected the status MCP App.'); +const serviceCatalog = Object.freeze({ + compiler: healthyCompilerStatus, + 'payments-api': Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'P95 latency', + status: 'failing' + }) + ]), + service: 'payments-api', + status: 'degraded', + summary: 'Payment latency is above the release threshold.' + }) +}); +const createStatusServer = ()=>{ + // The compiler stamps this project's identity into `agent-bundle/meta`, so + // the wire identity cannot drift from the config or package.json. + const server = new mcp_DXXb3Vv3_McpServer({ + name: meta_name, + version: (/* inlined export .version */"1.0.0") + }); + server.registerResource(app.name, app.resourceUri, { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + mimeType: app.mimeType + }, async (uri)=>({ + contents: [ + { + mimeType: app.mimeType, + text: app.html, + uri: uri.href + } + ] + })); + server.registerTool('show-status', { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + description: 'Show the health of one example service.', + inputSchema: schemas_object({ + service: schemas_enum([ + 'compiler', + 'payments-api' + ]) + }) + }, async ({ service })=>{ + const result = serviceCatalog[service]; + return { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + content: [ + { + text: result.summary, + type: 'text' + } + ], + structuredContent: result + }; + }); + return server; +}; +/** + * Default-exported server factory: `agent-bundle build` detects it and wraps + * this entry in the framework stdio lifecycle shell (console-to-stderr guard, + * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). + */ /* export default */ const mcp_status = (createStatusServer); + + + + + +//#region src/server/stdio.ts +/** +* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. +* +* This transport is only available in Node.js environments. +* +* @example +* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* const transport = new StdioServerTransport(); +* await server.connect(transport); +* ``` +*/ +var stdio_StdioServerTransport = class { + _readBuffer; + _started = false; + _closed = false; + constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); + } + onclose; + onerror; + onmessage; + _ondata = (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error) { + this.onerror?.(error); + this.close().catch(() => {}); + } + }; + _onerror = (error) => { + this.onerror?.(error); + }; + _onstdouterror = (error) => { + this.onerror?.(error); + this.close().catch(() => {}); + }; + /** + * Starts listening for messages on `stdin`. + */ + async start() { + if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + this._stdout.on("error", this._onstdouterror); + } + processReadBuffer() { + while (true) try { + const message = this._readBuffer.readMessage(); + if (message === null) break; + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + this._stdout.off("error", this._onstdouterror); + if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); + return new Promise((resolve, reject) => { + const json = serializeMessage(message); + let settled = false; + const onError = (error) => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + reject(error); + }; + const onDrain = () => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + resolve(); + }; + this._stdout.once("error", onError); + if (this._stdout.write(json)) { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + resolve(); + } else if (!settled) this._stdout.once("drain", onDrain); + }); + } +}; + +//#endregion +//#region src/server/serveStdio.ts +/** +* How long the probe-discard path waits for the probe instance to answer the +* requests it was delivered before closing it. The wait normally settles as +* soon as the DiscoverResult is handed to the wire (or immediately, when a +* delivered cancellation already settled the probe); the bound is a backstop +* so no edge can ever hold the connection's inbound pump indefinitely behind +* the discard. +*/ +const DISCARD_ANSWER_TIMEOUT_MS = 3e3; +/** +* The transport a pinned instance is connected to: a thin channel that writes +* through to the entry-owned wire transport and receives the messages the +* entry forwards. The wire transport itself is never handed to an instance — +* that is what lets the entry discard an optimistic probe instance (close the +* channel) without tearing down the connection. +*/ +var StdioConnectionChannel = class { + onclose; + onerror; + onmessage; + _closed = false; + /** Request ids the entry delivered to the instance that the instance has not yet answered. */ + _pendingRequests = /* @__PURE__ */ new Set(); + _drainWaiters = []; + constructor(_wire, _onInstanceClose, _outboundIntercept) { + this._wire = _wire; + this._onInstanceClose = _onInstanceClose; + this._outboundIntercept = _outboundIntercept; + } + async start() {} + async send(message, options) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + const { id } = message; + if (id !== void 0) this._settle(id); + } + if (this._closed) return; + if (this._outboundIntercept?.(message) === "handled") return; + return this._wire.send(message, options); + } + setProtocolVersion = (version) => { + this._wire.setProtocolVersion?.(version); + }; + /** Forwards one inbound message to the connected instance. */ + deliver(message, extra) { + if (this._closed) return; + if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); + else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0) this._settle(cancelledId); + } + this.onmessage?.(message, extra); + } + /** + * Resolves once every request delivered to the instance has been answered + * through {@linkcode send}, settled by a delivered cancellation, or the + * channel has been closed and nothing further can be answered. The wait is + * bounded by `timeoutMs` as a backstop so no edge can hold the caller + * indefinitely; resolves `false` only when the bound elapsed with requests + * still unanswered. Used by the probe-discard path so a probe request the + * entry accepted is never silently dropped. + */ + async whenRequestsAnswered(timeoutMs) { + if (this._closed || this._pendingRequests.size === 0) return true; + return await new Promise((resolve) => { + const waiter = () => { + clearTimeout(timer); + resolve(true); + }; + const timer = setTimeout(() => { + this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); + resolve(false); + }, timeoutMs); + this._drainWaiters.push(waiter); + }); + } + async close() { + if (this._closed) return; + this._closed = true; + this._pendingRequests.clear(); + this._releaseDrainWaiters(); + try { + this._onInstanceClose(); + } finally { + this.onclose?.(); + } + } + _settle(id) { + this._pendingRequests.delete(id); + if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); + } + _releaseDrainWaiters() { + const waiters = this._drainWaiters; + this._drainWaiters = []; + for (const waiter of waiters) waiter(); + } +}; +/** +* Classifies one message of the opening exchange with the same body-primary +* rules the HTTP entry applies per request: `initialize` is the legacy +* handshake unless it carries a valid modern envelope claim; a present claim +* is validated (never silently ignored); a claim-less message is 2025-era +* traffic. There is no header layer on stdio, so the body is the only signal. +*/ +function classifyOpeningMessage(message) { + const params = message.params; + if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { + const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (!hasEnvelopeClaim(params)) return { + kind: "legacy", + reason: "no-claim" + }; + const meta = requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return { + kind: "invalid-envelope", + issue: firstIssue + }; + const claimedVersion = envelopeClaimVersion(params); + if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { + kind: "unsupported-revision", + requested: claimedVersion ?? "unknown" + }; + return { + kind: "modern", + revision: claimedVersion, + classification: { + era: "modern", + revision: claimedVersion + } + }; +} +/** +* Serves MCP over stdio from a server factory, owning the era decision for +* the connection: the opening exchange selects the era, ONE instance from the +* factory is pinned for the connection lifetime, and everything after passes +* straight through to it. See the module documentation for the opening rules. +* +* ```ts +* import { serveStdio } from '@modelcontextprotocol/server/stdio'; +* +* serveStdio(() => { +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); +* // register tools/resources/prompts once — the same factory serves both eras +* return server; +* }); +* ``` +*/ +function serveStdio(factory, options = {}) { + const legacyMode = options.legacy ?? "serve"; + const wire = options.transport ?? new stdio_StdioServerTransport(); + let state = { phase: "opening" }; + /** Channel currently being discarded (its close must not tear the connection down). */ + let discarding; + let closing = false; + /** + * Whether the connection has been torn down (`handle.close()` or the wire + * closing). The opening arms re-check this after every await: a close can + * race factory construction, and the continuation must neither resurrect + * the connection state nor keep a late-resolved instance around. + */ + const isTornDown = () => closing || state.phase === "closed"; + const reportError = (error) => { + try { + options.onerror?.(error); + } catch {} + }; + const writeErrorResponse = (id, code, message, data) => wire.send({ + jsonrpc: "2.0", + id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }).catch((error) => reportError(stdio_toError(error))); + /** + * Entry-handled `subscriptions/listen` for this connection: holds the + * active subscriptions, serves inbound listen / cancelled-of-listen + * before the pinned instance is consulted, and rewrites the instance's + * outbound change notifications onto the active subscriptions. Only + * consulted on a modern-pinned connection — on a legacy connection + * change notifications pass straight through (the 2025 unsolicited + * delivery model is unchanged). + */ + const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); + /** Outbound intercept installed on a modern instance's channel. */ + const modernOutboundIntercept = (message) => { + if (!isJSONRPCNotification(message)) return void 0; + const routed = listenRouter.routeOutbound(message); + if (routed === "passthrough") return void 0; + for (const stamped of routed) wire.send({ + jsonrpc: "2.0", + ...stamped + }).catch((error) => reportError(stdio_toError(error))); + return "handled"; + }; + /** + * Entry-handled inbound listen routing for a modern-pinned connection. + * Returns `true` when the message was served at the entry and must NOT + * be delivered to the pinned instance. + */ + const tryServeListen = async (message) => { + if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { + const meta = requestMetaOf(message.params); + const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { + key: "_meta", + problem: "the per-request envelope is required on protocol revision 2026-07-28" + }; + const claimedVersion = envelopeClaimVersion(message.params); + let reply; + if (issue !== void 0) reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` + } + }; + else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedVersion ?? "unknown" + }); + reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: error.code, + message: error.message, + data: error.data + } + }; + } else reply = listenRouter.serve(message); + await wire.send("error" in reply ? reply : { + jsonrpc: "2.0", + method: reply.method, + params: reply.params + }).catch((error) => reportError(stdio_toError(error))); + return true; + } + if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; + } + return false; + }; + /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ + const answerLegacyRejection = (request, reason, requestedVersion) => { + const rejection = modernOnlyStrictRejection({ + kind: "legacy", + reason, + ...requestedVersion !== void 0 && { requestedVersion } + }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (rejection === void 0) return Promise.resolve(); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); + return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); + }; + const onInstanceClosed = (channel) => { + if (closing || channel === discarding) return; + closeAll(); + }; + const connectInstance = async (era, revision) => { + const product = await factory({ era }); + const server = product instanceof McpServer ? product.server : product; + if (era === "modern") { + setNegotiatedProtocolVersion(server, revision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); + } + const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); + await product.connect(channel); + return { + product, + channel + }; + }; + /** Closes an instance whose factory resolved only after the connection was torn down. */ + const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); + const discardProbeInstance = async (instance) => { + discarding = instance.channel; + try { + if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); + await instance.product.close(); + } catch (error) { + reportError(stdio_toError(error)); + } finally { + discarding = void 0; + } + }; + const processMessage = async (message) => { + if (state.phase === "closed") return; + if (state.phase === "pinned") { + if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { + await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); + return; + } + if (state.era === "modern" && await tryServeListen(message)) return; + state.instance.channel.deliver(message); + return; + } + if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { + reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); + return; + } + const opening = classifyOpeningMessage(message); + switch (opening.kind) { + case "invalid-envelope": { + const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); + else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); + return; + } + case "unsupported-revision": + if (isJSONRPCRequest(message)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: opening.requested + }); + reportError(error); + await writeErrorResponse(message.id, error.code, error.message, error.data); + } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); + return; + case "modern": + if (isJSONRPCRequest(message) && message.method === "server/discover") { + if (state.phase === "probe") { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "probe", + instance + }; + instance.channel.deliver(message, { classification: opening.classification }); + return; + } + if (state.phase === "probe") { + if (isJSONRPCNotification(message)) { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + state = { + phase: "pinned", + era: "modern", + instance: state.instance + }; + } else { + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "modern", + instance + }; + } + if (await tryServeListen(message)) return; + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + case "legacy": { + if (legacyMode === "reject") { + if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); + return; + } + if (state.phase === "probe") { + await discardProbeInstance(state.instance); + if (isTornDown()) return; + state = { phase: "opening" }; + } + const instance = await connectInstance("legacy"); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "legacy", + instance + }; + state.instance.channel.deliver(message); + return; + } + } + }; + const queue = []; + let pumping = false; + const pump = async () => { + if (pumping) return; + pumping = true; + try { + while (queue.length > 0) { + const message = queue.shift(); + try { + await processMessage(message); + } catch (error) { + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); + reportError(stdio_toError(error)); + } + } + } finally { + pumping = false; + } + }; + const closeAll = async () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); + if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + await wire.close().catch((error) => reportError(stdio_toError(error))); + }; + wire.onmessage = (message) => { + queue.push(message); + pump(); + }; + wire.onerror = (error) => { + reportError(error); + if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); + }; + wire.onclose = () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + }; + const started = wire.start().catch((error) => { + reportError(stdio_toError(error)); + throw error; + }); + started.catch(() => {}); + return { close: async () => { + await started.catch(() => {}); + await closeAll(); + } }; +} +function stdio_toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} + +//#endregion + +//# sourceMappingURL=stdio.mjs.map +const defaultHeartbeatIntervalMs = 300000; +const defaultActivityThrottleMs = 60000; +const defaultShutdownTimeoutMs = 5000; +const defaultHeartbeatName = 'agent-bundle'; +const redirectConsoleToStderr = ()=>{ + const originalStdoutWrite = process.stdout.write.bind(process.stdout); + const stderrConsole = new console.Console({ + stderr: process.stderr, + stdout: process.stderr + }); + const methods = [ + 'debug', + 'dir', + 'error', + 'info', + 'log', + 'trace', + 'warn' + ]; + for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); + process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); + return Object.freeze({ + restoreProtocolStdout: ()=>{ + process.stdout.write = originalStdoutWrite; + } + }); +}; +const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ + const startedAt = Date.now(); + let lastActivityAt = startedAt; + let lastActivityLogAt = 0; + const log = (reason)=>{ + const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); + const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); + writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); + }; + const timer = setInterval(()=>log('interval'), intervalMs); + timer.unref?.(); + return Object.freeze({ + log, + noteActivity: ()=>{ + lastActivityAt = Date.now(); + if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { + lastActivityLogAt = lastActivityAt; + log('activity'); + } + }, + stop: ()=>clearInterval(timer) + }); +}; +const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ + const heartbeat = createHeartbeat({ + ...void 0 === activityThrottleMs ? {} : { + activityThrottleMs + }, + ...void 0 === heartbeatIntervalMs ? {} : { + intervalMs: heartbeatIntervalMs + }, + ...void 0 === serverName ? {} : { + name: serverName + }, + writeLine: heartbeatEnabled ? writeLine : ()=>void 0 + }); + const keepalive = setInterval(()=>void 0, 60000); + keepalive.unref?.(); + let shuttingDown = false; + const shutdown = async (exitCode = 0)=>{ + if (shuttingDown) return; + shuttingDown = true; + signals.off('SIGINT', handleSigint); + signals.off('SIGTERM', handleSigterm); + stdin.off?.('end', handleStdinEnd); + clearInterval(keepalive); + heartbeat.stop(); + await Promise.race([ + Promise.allSettled([ + Promise.resolve().then(()=>transport.close()), + Promise.resolve().then(()=>server.close()) + ]), + new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) + ]); + exit(exitCode); + }; + const handleSigint = ()=>{ + shutdown(130); + }; + const handleSigterm = ()=>{ + shutdown(143); + }; + const handleStdinEnd = ()=>{ + shutdown(0); + }; + signals.on('SIGINT', handleSigint); + signals.on('SIGTERM', handleSigterm); + stdin.once?.('end', handleStdinEnd); + transport.onclose = ()=>{ + shutdown(0); + }; + await server.connect(transport); + const originalOnMessage = transport.onmessage; + transport.onmessage = (message, extra)=>{ + heartbeat.noteActivity(); + originalOnMessage?.(message, extra); + }; + return Object.freeze({ + heartbeat, + shutdown + }); +}; +const runGeneratedStdioMcpEntry = async (options)=>{ + const guard = redirectConsoleToStderr(); + const entry = await options.loadEntry(); + const factory = entry.default; + if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); + const server = await factory(); + const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); + guard.restoreProtocolStdout(); + const transport = new StdioServerTransport(); + return runStdioServer({ + ...options.lifecycle, + server, + serverName: options.serverName, + transport: transport + }); +}; + + + +await runGeneratedStdioMcpEntry({ + loadEntry: ()=>Promise.resolve(status_namespaceObject), + serverName: "status" +}); + +export {}; diff --git a/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs new file mode 100644 index 000000000..a6f274bf6 --- /dev/null +++ b/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs @@ -0,0 +1,60 @@ +import { readFile } from "node:fs/promises"; + + + + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + +const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); +/** + * `agent-bundle build` detects the `main` export and generates the process + * envelope (argv, awaiting, numeric-return exit-code adoption) around it. + */ const main = async ()=>{ + try { + const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); + if (!isHealthyCompilerFixture(fixture)) { + throw new Error('compiler fixture must contain the exact healthy compiler status'); + } + process.stdout.write('Compiler fixture is healthy.\n'); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const check_service_fixture_entry_main = main; +if (typeof check_service_fixture_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/mcp-app/src/scripts/check-service-fixture.ts"); +} +const code = await check_service_fixture_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md new file mode 100644 index 000000000..8f91a79d7 --- /dev/null +++ b/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md @@ -0,0 +1,33 @@ +--- +name: service-readiness +description: Reviews service health evidence and records an auditable readiness decision. +--- +# Service readiness + +## When to use + +Use this Skill when a release, incident decision, or service handoff needs a +clear health verdict backed by named checks and current evidence. + +## Required resources + +- Apply [the service status policy](references/status-policy.md) before + classifying a healthy, degraded, or blocked result. +- Deliver the decision with [the readiness report](assets/readiness-report.md). + +## Workflow + +1. Identify the service and collect its current summary and every labelled + check. Record the command, time, result, and evidence source. +2. Classify any failing check with the status policy. A degraded service is not + release-ready until its failing check has an approved mitigation. +3. State the readiness verdict only after confirming availability and the + service-specific release threshold. +4. Complete the report with the status, checks, evidence, owner, and next + action. Do not omit a failing check from the final decision. + +## Final report requirements + +State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the +service summary; list each labelled check and its status; identify the owner +and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md new file mode 100644 index 000000000..3da5d52ea --- /dev/null +++ b/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md @@ -0,0 +1,22 @@ +# Service readiness report + +## Verdict + +State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. + +## Evidence + +Record the collection time, command or artifact, service summary, and source. + +## Checks + +List every labelled check with its observed status and release threshold. + +## Findings and mitigation + +For each non-passing check, record the impact, owner, mitigation, due date, +and the evidence required to clear it. + +## Next action + +Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md new file mode 100644 index 000000000..7e5766172 --- /dev/null +++ b/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md @@ -0,0 +1,22 @@ +# Service status policy + +## Evidence standard + +Readiness evidence must identify the service, collection time, check label, +observed status, and source command or artifact. Missing or stale evidence is +not a passing check. + +## Status classification + +- **Healthy**: every required release check is passing. +- **Degraded**: availability remains sufficient, but a release threshold such + as P95 latency is failing. Record an owner and mitigation before release. +- **Blocked**: availability or a critical safety check is failing. Do not + release until new passing evidence is collected. +- **Needs evidence**: the service or any required check cannot be verified. + +## Release decision + +Issue `ready` only for a healthy service with current evidence. A degraded +service needs an explicit mitigation decision; a blocked service cannot pass; +and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json b/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json new file mode 100644 index 000000000..37ef3be4a --- /dev/null +++ b/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"mcp-app-example"},"name":"mcp-app-example-marketplace","plugins":[{"category":"Productivity","name":"mcp-app-example","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json b/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json new file mode 100644 index 000000000..a86a5db3f --- /dev/null +++ b/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","interface":{"capabilities":["mcp","hooks","skills"],"category":"Productivity","defaultPrompt":["Help me use mcp-app-example."],"developerName":"mcp-app-example","displayName":"mcp-app-example","longDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","shortDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation."},"mcpServers":"./.mcp.json","name":"mcp-app-example","skills":"./skills/","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/codex/.mcp.json b/examples/mcp-app/artifact/codex/.mcp.json new file mode 100644 index 000000000..8a84f9c2f --- /dev/null +++ b/examples/mcp-app/artifact/codex/.mcp.json @@ -0,0 +1 @@ +{"mcpServers":{"status":{"args":["./mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"./","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"./"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/codex/INSTALL.md b/examples/mcp-app/artifact/codex/INSTALL.md new file mode 100644 index 000000000..f93c7ff0b --- /dev/null +++ b/examples/mcp-app/artifact/codex/INSTALL.md @@ -0,0 +1,16 @@ +# Install mcp-app-example + +A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Codex + +Codex installs this bundle from its local marketplace snapshot: + +```sh +codex plugin marketplace add ./ +codex plugin add mcp-app-example@mcp-app-example-marketplace +``` diff --git a/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json new file mode 100644 index 000000000..a765aa4b5 --- /dev/null +++ b/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json @@ -0,0 +1,9 @@ +{ + "service": "compiler", + "status": "healthy", + "summary": "Compiler service is ready for release.", + "checks": [ + { "label": "Availability", "status": "passing" }, + { "label": "Build queue", "status": "passing" } + ] +} diff --git a/examples/mcp-app/artifact/codex/hooks/hooks.json b/examples/mcp-app/artifact/codex/hooks/hooks.json new file mode 100644 index 000000000..eb4f61756 --- /dev/null +++ b/examples/mcp-app/artifact/codex/hooks/hooks.json @@ -0,0 +1 @@ +{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs new file mode 100644 index 000000000..e3a4ce01c --- /dev/null +++ b/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs @@ -0,0 +1,254 @@ +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/hooks/session-start.ts +var session_start_namespaceObject = {}; +__webpack_require__.r(session_start_namespaceObject); +__webpack_require__.d(session_start_namespaceObject, { + "default": () => (session_start) }); + + +/* export default */ const session_start = ((event)=>({ + additionalContext: [ + `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, + `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, + 'Use show-status for compiler or payments-api when live service evidence is needed.' + ].join(' '), + outcome: 'continue' + })); + + +const target = "codex"; +const canonicalEvent = "sessionStart"; +const nativeEvent = "SessionStart"; +const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); +const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); +const decodeCodexNative = (nativeInput)=>({ + agentId: nativeInput.agent_id, + agentTranscriptPath: nativeInput.agent_transcript_path, + agentType: nativeInput.agent_type, + cwd: nativeInput.cwd, + effort: nativeInput.effort, + hookEventName: nativeInput.hook_event_name, + lastAssistantMessage: nativeInput.last_assistant_message, + model: nativeInput.model, + permissionMode: nativeInput.permission_mode, + promptId: nativeInput.prompt_id, + sessionId: nativeInput.session_id, + source: nativeInput.source, + stopHookActive: nativeInput.stop_hook_active, + toolInput: nativeInput.tool_input, + toolName: nativeInput.tool_name, + toolResponse: nativeInput.tool_response, + toolUseId: nativeInput.tool_use_id, + transcriptPath: nativeInput.transcript_path, + turnId: nativeInput.turn_id + }); +const encodeCodexNative = (canonicalInput)=>defined({ + hook_event_name: nativeEvent, + agent_id: canonicalInput.agentId, + agent_transcript_path: canonicalInput.agentTranscriptPath, + agent_type: canonicalInput.agentType, + cwd: canonicalInput.cwd, + effort: canonicalInput.effort, + last_assistant_message: canonicalInput.lastAssistantMessage, + model: canonicalInput.model, + permission_mode: canonicalInput.permissionMode, + prompt_id: canonicalInput.promptId, + session_id: canonicalInput.sessionId, + source: canonicalInput.source, + stop_hook_active: canonicalInput.stopHookActive, + tool_input: canonicalInput.toolInput, + tool_name: canonicalInput.toolName, + tool_response: canonicalInput.toolResponse, + tool_use_id: canonicalInput.toolUseId, + transcript_path: canonicalInput.transcriptPath, + turn_id: canonicalInput.turnId + }); +const decodeNative = decodeCodexNative; +const encodeNative = encodeCodexNative; +const fail = (message)=>{ + throw new Error(`Agent Bundle hook error: ${message}`); +}; +const validateResult = (result)=>{ + if (result === undefined) return undefined; + if (!isRecord(result)) fail("handler must return void or a result object"); + const allowed = new Set([ + "outcome", + "reason", + "updatedInput", + "additionalContext" + ]); + for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); + if (result.outcome !== undefined && ![ + "continue", + "deny", + "stop" + ].includes(result.outcome)) fail("handler result outcome is invalid"); + if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); + if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); + if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); + const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; + if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); + if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); + if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); + if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); + if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); + if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); + if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); + return result; +}; +const encodeOutput = (result)=>{ + if (result === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (result.outcome === "deny") return defined({ + decision: "block", + reason: result.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = defined({ + additionalContext: result.additionalContext, + hookEventName: nativeEvent, + permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, + permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, + updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined + }); + return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { + hookSpecificOutput: output + }; +}; +const decodeOutput = (nativeOutput)=>{ + if (nativeOutput === undefined) return undefined; + if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { + if (nativeOutput.decision === "block") return defined({ + outcome: "deny", + reason: nativeOutput.reason + }); + if (canonicalEvent === "agentStop" && target === "claude" && 0) {} + return undefined; + } + const output = nativeOutput.hookSpecificOutput; + if (!isRecord(output)) fail("native hook output is malformed"); + return defined({ + additionalContext: output.additionalContext, + outcome: output.permissionDecision === "deny" ? "deny" : "continue", + reason: output.permissionDecisionReason, + updatedInput: output.updatedInput + }); +}; +const requireString = (input, field)=>{ + if (typeof input[field] !== "string") fail(`native ${field} must be a string`); +}; +const requireNullableString = (input, field)=>{ + if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); +}; +const validateNativeInput = (input)=>{ + requireString(input, "session_id"); + if (true) requireNullableString(input, "transcript_path"); + else {} + requireString(input, "cwd"); + if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); + if (input.prompt_id !== undefined) requireString(input, "prompt_id"); + if (input.permission_mode !== undefined) requireString(input, "permission_mode"); + if (input.model !== undefined) requireString(input, "model"); + if (canonicalEvent === "sessionStart") { + requireString(input, "source"); + return; + } + if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { + requireString(input, "tool_name"); + if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); + requireString(input, "tool_use_id"); + if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); + return; + } + if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { + requireString(input, "agent_id"); + requireString(input, "agent_type"); + if (true) { + requireString(input, "turn_id"); + requireString(input, "model"); + requireString(input, "permission_mode"); + if (![ + "default", + "acceptEdits", + "plan", + "dontAsk", + "bypassPermissions" + ].includes(input.permission_mode)) fail("native permission_mode is invalid"); + } + if (canonicalEvent === "agentStart") return; + if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); + requireNullableString(input, "agent_transcript_path"); + requireNullableString(input, "last_assistant_message"); + return; + } + if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); + if (true) requireNullableString(input, "last_assistant_message"); + else {} +}; +const run = async ()=>{ + const handler = Reflect.get(session_start_namespaceObject, "default"); + if (typeof handler !== "function") fail("default export must be a function"); + let raw = ""; + for await (const chunk of process.stdin)raw += chunk; + if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); + let input; + try { + input = JSON.parse(raw); + } catch { + fail("stdin must contain exactly one JSON value"); + } + if (!isRecord(input)) fail("stdin JSON value must be an object"); + const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; + const nativeInput = simulation ? encodeNative(input) : input; + validateNativeInput(nativeInput); + const event = decodeNative(nativeInput); + const result = validateResult(await handler(event, { + nativeEvent: nativeEvent, + nativeInput, + target: target + })); + const nativeOutput = encodeOutput(result); + const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; + if (output !== undefined) process.stdout.write(JSON.stringify(output)); +}; +if (import.meta.main) { + await run().catch((error)=>{ + process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); + process.exitCode = 1; + }); +} + +export {}; diff --git a/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs new file mode 100644 index 000000000..29189bf45 --- /dev/null +++ b/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs @@ -0,0 +1,30761 @@ +import node_process from "node:process"; + +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/mcp/status.ts +var status_namespaceObject = {}; +__webpack_require__.r(status_namespaceObject); +__webpack_require__.d(status_namespaceObject, { + createStatusServer: () => (createStatusServer), + "default": () => (mcp_status) }); + + +// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +var stdio_namespaceObject = {}; +__webpack_require__.r(stdio_namespaceObject); +__webpack_require__.d(stdio_namespaceObject, { + StdioServerTransport: () => (stdio_StdioServerTransport) }); + + +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion + +//#region ../core-internal/src/validators/dialects.ts +/** +* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). +*/ +const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); +const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); +const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); +const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); +/** +* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with +* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so +* wire-layer callers can consult it for documents whose dialect may be unsupported. +*/ +function declares2019Dialect($schema) { + return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); +} +/** +* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means +* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the +* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling +* provider's escape hatch in that message. +*/ +function declaredDialect(schema, remedy) { + if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; + const declared = schema.$schema.replace(/#$/, ""); + if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; + if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; + if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); +} + +//#endregion + +//# sourceMappingURL=dialects-DoSzNhcb.mjs.map + +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function toZod() { + return (schema) => schema; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function util_cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function util_esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function util_isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const util_allowsEval = /* @__PURE__*/ util_cached(() => { + // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. + if (globalConfig.jitless) { + return false; + } + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (util_isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (util_isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); +const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined", +]))); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; + }); +} +// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + // `for...in` skips symbols, so a symbol in the mask would select nothing + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + assignProp(newShape, key, currDef.shape[key]); + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values + const existingShape = schema._zod.def.shape; + for (const key of Reflect.ownKeys(shape)) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function merge(a, b) { + if (!b?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [], + }); + return clone(a, def); +} +function partial(Class, schema, mask, name = "partial") { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + else { + // the spread copies symbol keys; `for...in` would not reach them + for (const key of Reflect.ownKeys(oldShape)) { + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +function util_required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key of Reflect.ownKeys(oldShape)) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + }); + return clone(schema, def); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) { + (_a = issues[i]).schema ?? (_a.schema = inst); + } +} +function finalizeIssue(iss, ctx, config) { + var _a; + // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a = iss).schema ?? (_a.schema = iss.inst); + else + iss.schema = iss.inst; + } + // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; + const message = iss.message + ? iss.message + : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(schemaError?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"); + const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +const highSurrogate = /[\uD800-\uDBFF]/; +// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function util_issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class util_Class { + constructor(..._args) { } +} +////////// PROTOTYPE INSTALLERS ////////// +// +// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. +/** + * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. + * + * Call this from a `proto` initializer, which runs once per prototype — never per instance. + */ +function util_members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was + if (desc.get) + Object.defineProperty(proto, key, { ...desc, enumerable: false }); + // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` + else + defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function util_own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return util_own(inst, key, value, false); +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method + return this == null ? fn : util_own(this, key, fn.bind(this)); + }, + set(value) { + util_own(this, key, value); + }, + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. + return sentinel in proto ? undefined : proto; +} +// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. +let installing; +// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + return undefined; + }, +}; +/** + * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s + * constructor, computed from the internals object itself and cached there on + * first read. One accessor per constructor rather than one per instance. + */ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. + installing = undefined; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } + catch (err) { + // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + }, + }); +} +/** + * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own + * data property. One accessor per constructor rather than one per instance, because an own accessor + * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. + */ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. + const desc = { configurable: true, writable: true, enumerable, value: undefined }; + Object.defineProperty(this, key, desc); + // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + }, + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +var core_a; + +/** A special constant with type `never` */ +const NEVER = /*@__PURE__*/ Object.freeze({ + status: "aborted", +}); +/* Shared descriptor for installing `_zod`; defineProperty reads it + * synchronously, so reusing one object avoids a per-instance allocation. */ +const _zodDesc = { value: undefined, enumerable: false }; +// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error +let _E = "captureStackTrace" in Error ? Error : null; +// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } + catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } + finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, +/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ +proto, params) { + // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. + const zodProto = {}; + // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. + const initialized = protoMembers && new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } + finally { + // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. + _zodDesc.value = undefined; + } + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + util_members(target, protoMembers); + } + } + // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) + continue; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. + inst._zod.deferred = undefined; + } + // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function core_config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +class $ZodCyclicError extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +} +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +// Receivers prefix paths in place, so the cache and every hand-out need their own copies. +function cloneIssues(issues) { + return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack) { + const cached = recursive.get(inst); + if (cached !== undefined) + return cached; + // Relative to the walk in progress, so not cached. + if (stack.has(inst)) + return true; + stack.add(inst); + let result = false; + const check = (child) => { + if (!result && child?._zod && isRecursive(child, stack)) + result = true; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen + for (const key of Reflect.ownKeys(def.shape)) + check(def.shape[key]); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) + check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) + check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + // reading `_zod.innerType` resolves the getter once and caches it + case "lazy": + check(inst._zod.innerType); + break; + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + // a new built-in kind becomes a compile error here + kind; + // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code + for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) + continue; + const value = desc.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check(value); + else if (Array.isArray(value)) + for (const el of value) + check(el); + } + } + } + stack.delete(inst); + recursive.set(inst, result); + return result; +} +/** + * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. + * Exported for `z.compile`, which refuses to compile such a schema: cycle + * breaking is driven from here off state keyed on the parse context, and a + * generated fast path has no context to key on. + */ +function isRecursiveSchema(inst) { + return isRecursive(inst, new Set()); +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = new Map(); + state.buckets.set(inst, bucket); + } + return bucket; +} +// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. +let handoff; +// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. +const memoizer_open = []; +const memoizer_memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = undefined; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + memoizer_open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes + let lastCtx; + let lastBucket; + // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === undefined) { + isRecursiveInst = isRecursive(inst, new Set()); + if (!isRecursiveInst) { + // Nothing here can ever fire, so take it back out. + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + } + const input = payload.value; + if (input === null || typeof input !== "object") + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: new Map(), backEdges: undefined }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } + else { + // Still being parsed: its own checks cover it, so skip them here. + payload.memo = true; + state.backEdges ?? (state.backEdges = new Set()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = memoizer_open.length; + const result = base(payload, ctx); + handoff = undefined; + // A container that rejected its input outright allocated nothing. + const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; + // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memoizer_memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); +} + + +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?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)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. +const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const regexes_ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/; +const mac = (delimiter) => { + const escapedDelim = util.escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const regexes_base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; +const httpProtocol = /^https?$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 +const e164 = /^\+[1-9]\d{6,14}$/; +// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). +const creditCard = /^\d(?:[ -]?\d){11,18}$/; +const dateSource = `(?:(?:\\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])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because + * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it + * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function regexes_anchor(source) { + return new RegExp(`^${source}$`); +} +const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : args.seconds + ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function regexes_time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const opts = ["Z"]; + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const regexes_string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const regexes_boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const regexes_hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); +const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); +const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); +const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); +const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); +const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); + +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ +const _whenHasSize = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; +}; +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; +}; +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. + const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. + const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 + ? codePointLength(input) + : units; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 + ? codePointLength(input) + : units; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + // `String.prototype.includes(sub, position)` matches `sub` at `position` + // OR LATER, so the pattern must allow at least `position` leading chars + // (`{N,}`), not exactly `position` chars (`{N}`). + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +class Doc { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); + return factory(...Object.values(this.closed)); + } +} + + + +/* Computing the message eagerly is expensive (pretty-printed JSON of all + * issues), so defer it until first read. The accessor functions and + * descriptors are shared across instances to keep error construction + * cheap; the computed message is cached on the internals object. The + * setter preserves plain assignment semantics for consumers that + * overwrite `message`. */ +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true, +}; +const errors_zodDesc = { value: undefined, enumerable: false }; +const _issuesDesc = { value: undefined, enumerable: false }; +/* Prototypes that already carry the lazy `toString`. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const errors_initializer = (inst, def) => { + inst.name = "$ZodError"; + errors_zodDesc.value = inst._zod; + Object.defineProperty(inst, "_zod", errors_zodDesc); + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + // Clear the shared slots; a retained `value` pins the last error's issues. + errors_zodDesc.value = undefined; + _issuesDesc.value = undefined; + Object.defineProperty(inst, "message", _messageDesc); + /* `toString` lives as a non-enumerable lazy getter on the shared + * prototype; on first access it caches a per-instance closure so + * detached usage still works. */ + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + }, + }); + } +}; +const $ZodError = $constructor("$ZodError", errors_initializer); +const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { + Parent: Error, +}); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member + * ("toString", "constructor") would otherwise read through to the prototype, and assigning + * "__proto__" would hit the setter instead of creating a key. */ +function errors_node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } + else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue)); + i++; + continue; + } + // A path element may collide with an inherited property name such as + // "__proto__" or "constructor". Truthiness checks read the prototype + // (so no node is created, then ._errors.push throws), and bracket + // assignment of "__proto__" hits the setter instead of creating an + // own key. Guard the read with hasOwnProperty and create the node + // with defineProperty so any path element becomes a real own key. + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + const node = curr[el]; + if (terminal) { + node._errors.push(mapper(issue)); + } + curr = node; + i++; + } + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + // el may collide with an inherited property name ("__proto__", + // "constructor", ...); ??= reads the prototype so the node is never + // created and curr.errors.push throws. Guard with hasOwnProperty and + // create the node with defineProperty so "__proto__" becomes a real + // own key rather than invoking the prototype setter. + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + + + + +// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +const parse_parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); +const parse_parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +// registry mirrors of the compiler's sentinels, so this module never imports the compiler +const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); +const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); +// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. +const parse_validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== undefined && validator(value) !== COMPILE_INVALID) + return true; + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } + else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + return result.issues.length === 0; +} +// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw +const parse_validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +const parse_encode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const encode = /* @__PURE__*/ parse_encode($ZodRealError); +const parse_decode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decode = /* @__PURE__*/ parse_decode($ZodRealError); +const parse_encodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); + }; + return fn; +}; +const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); +const parse_decodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); + +const versions_version = { + major: 4, + minor: 5, + patch: 4, +}; + + + + + + + + +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const defChecks = inst._zod.def.checks; + // if inst is itself a checks.$ZodCheck, run it as a check + const checks = inst._zod.traits.has("$ZodCheck") + ? [inst, ...(defChecks ?? [])] + : defChecks?.length + ? [...defChecks] + : []; + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) + return payload; + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; +function standardProps(inst) { + return { + validate: (value) => { + try { + return toStandardResult(safeParse(inst, value)); + } + catch (_) { + return safeParseAsync(inst, value).then(toStandardResult); + } + }, + vendor: "zod", + version: 1, + }; +} + +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } + else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL constructor rejected the input. */ +const URL_UNPARSEABLE = 2; +/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ +function parseURLObject(trimmed, def) { + // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + // @ts-ignore + return new URL(trimmed); + } + catch { + return URL_UNPARSEABLE; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + const url = parseURLObject(trimmed, def); + if (url === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + if (def.protocol && !urlProtocolOk(url, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + // Set the output value based on normalize flag + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema + if (def.local || def.precision === -1) { + inst._zod.bag.laxFormat = true; + inst._zod.onattach.push((s) => { + s._zod.bag.laxFormat = true; + }); + } +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes_date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes_time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + try { + // @ts-ignore + new URL(`http://[${value}]`); + return true; + } + catch { + return false; + } +} +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes_ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + // atob ignores whitespace, so reject it up front. + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes_base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodCreditCard ////////////////////////////// +const CC_SANITIZE = /[- ]/g; +/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ +function isLuhnAlgo(digits) { + let length = digits.length; + let bit = 1; + let sum = 0; + while (length) { + const value = +digits[--length]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input) { + if (!regexes.creditCard.test(input)) + return false; + return isLuhnAlgo(input.replace(CC_SANITIZE, "")); +} +const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { + // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. + def.pattern ?? (def.pattern = regexes.creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? String(input) + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } + if (result.issues.length) { + // For optional-in/out schemas, ignore errors on absent keys. + if (optin !== undefined && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && optin === undefined) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [key], + }); + } + return; + } + if (result.value === undefined) { + if (isPresent) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +// one shared instance; a fresh [] per schema cost 56 bytes retained +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + // aliases `keys` when there are no symbols, so a string-only shape keeps one array + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + for (const key in input) { + // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. + if (keySet.has(key)) + continue; + // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. +const propShapes = new WeakMap(); +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + // const sh = def.shape; + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + propShapes.set(def, sh); + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh, + }); + propShapes.set(def, newSh); + return newSh; + }, + }); + } + const _normalized = util_cached(() => normalizeDef(def)); + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, new Set()); + } + for (const v of field.values) + propValues[key].add(v); + // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. + if (field.optin !== undefined) + propValues[key].add(undefined); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value; + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + for (const key of value.allKeys) { + if (key === "__proto__") + continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = util_cached(() => normalizeDef(def)); + const memo = globalConfig.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope + const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + // Prefixes in place, like util.prefixIssues does for every interpreted path. + const prefixStr = (id, k) => ` + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== undefined; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } + else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + } + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${id}.value === undefined) { + if (${isPresent}) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone + return doc.compile(); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") + ? "defaulted" + : zod.def.options.some((o) => o._zod.optin !== undefined) + ? "optional" + : undefined); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; + return final; + } + if (matches.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + matches, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}))); +/** Returns the option of `union` whose discriminator claims `value`. */ +function getDiscriminatedOption(union, value) { + const internals = union._zod; + let map = internals.bag.optionsMap; + if (!map) { + map = new Map(); + const { options, discriminator } = internals.def; + for (const option of options) { + // First declaration wins, matching the order the parse path resolves a duplicate in. + for (const v of option._zod.propValues?.[discriminator] ?? []) + if (!map.has(v)) + map.set(v, option); + } + internals.bag.optionsMap = map; + } + return map.get(value); +} +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazyInternal(inst, "propValues", (zod) => { + const propValues = {}; + for (const option of zod.def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, new Set()); + } + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. + def.options.forEach((option, i) => { + const propShape = propShapes.get(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); + } + }); + const disc = util_cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + // Fall back to union matching when the fast discriminator path fails: + // - explicitly enabled via unionFallback, or + // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") + continue; + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. + const unrecKeys = new Map(); + let unrecIssue; + const keyIssues = new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } + else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; + } + else { + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); + } + for (const iss of right.issues) { + if (!collect(iss, "r")) + result.issues.push(iss); + } + // Report only keys rejected by BOTH sides + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } + } + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + if (aborted(result)) + return result; + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array", + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array", + }); + } + } + // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } + else { + itemResults[i] = r; + } + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}))); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. + const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...util.prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + // Drop trailing slots that produced `undefined` for absent input + // (the array analog of an absent optional key on an object). The + // `i >= input.length` floor is critical: an explicit `undefined` + // *inside* the input must be preserved even when the schema is + // optional-out (e.g. `z.string().or(z.undefined())` accepting an + // explicit undefined value). + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { + final.value.length = i; + } + else { + break; + } + } + return final; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + // A declared __proto__ is stripped but is not an unrecognized key. + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + if (def.mode === "loose") { + // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into + if (key === "__proto__") + continue; + payload.value[key] = input[key]; + } + else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. + let unrecognized; + // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + } + continue; + } + // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + const values = new Set(def.values); + inst._zod.values = values; + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(def.values.length + ? `^(${def.values + .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) + .join("|")})$` + : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. + payload.value = result.issues.length ? undefined : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + defineLazyInternal(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? new Set([...values, undefined]) : undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. + if (def.innerType._zod.optin !== "defaulted") + return payload; + // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + // Call parent init - inherits optin/optout = "optional" + $ZodOptional.init(inst, def); + // Override values/pattern to NOT add undefined + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + // Override parse to just delegate (no undefined handling) + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; + }); + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new core.$ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. + if (result.memo) + payload.memo = true; + return payload; + } + // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + }, + input: payload.value, + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) { + return result.then((result) => handleCatchResult(payload, result, def, ctx)); + } + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}))); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. + if (!payload.memo) + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. + Object.defineProperty(inst, "_def", { value: def }); + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. + return Object.defineProperty(function (...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return Object.defineProperty(async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. + defineLazy(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } +} + +var registries_a; +const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); +const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registries_registry() { + return new $ZodRegistry(); +} +(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + + + + + +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link _cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _creditCard(Class, params) { + return new Class({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +const TimePrecision = (/* unused pure expression or super */ null && ({ + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +})); +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ + type: "any", + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return _gt(0, params); +} +// negative +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return _lt(0, params); +} +// nonpositive +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum, + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length, + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes, + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _properties(shape) { + return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +// @__NO_SIDE_EFFECTS__ +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +// @__NO_SIDE_EFFECTS__ +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); + }, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params), + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function api_meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = util.normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? schemas.$ZodCodec; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + codec._zod.bag.truthy = truthyArray; + codec._zod.bag.falsy = falsyArray; + codec._zod.bag.case = params.case ?? "insensitive"; + return codec; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = util.normalizeParams(_params); + const def = { + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + + + +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + sharedDefsExtractedFor: undefined, + sharedEmitDoneFor: undefined, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? undefined, + }; +} +/** + * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws + * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a + * custom JSON Schema was written into `json`, in which case the caller must not write its own. + */ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" + ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) + : ctx.unrepresentable; + if (result === "any") + return false; + if (result === undefined || result === "throw") + throw new Error(message); + Object.assign(json, result); + return true; +} +function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = undefined; + ctx.sharedEmitDoneFor = undefined; + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + // Also set ref if processor didn't (for inheritance) + if (!result.ref) + result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && "_prefault" in result.schema) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; + // Track ids to detect duplicates across different schemas + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } + // self-contained schema + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; + }; + // stored cached version in `def` property remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) + return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types.includes(member)) + types.push(member); + } + } + delete schema.anyOf; + // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, + * an annotation like `description` — makes a member unfoldable, so a constraint this does not + * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + // A boolean subschema is legal JSON Schema and carries no keywords to fold. + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required = new Set(); + for (const object of objects) { + for (const key in object.properties) { + // `in` would report a `__proto__` key as already present via the prototype chain and skip it. + if (Object.prototype.hasOwnProperty.call(properties, key)) + continue; + // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === undefined) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); + } + const merged = parts.length === 1 + ? parts[0] + : (foldObjects(parts) ?? { allOf: parts }); + assignProp(properties, key, merged); + } + for (const key of object.required ?? []) + required.add(key); + } + const folded = { type: "object", properties }; + if (required.size) + folded.required = [...required]; + // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. + if (objects.every((object) => object.additionalProperties === false)) { + folded.additionalProperties = false; + } + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two + * closed object members reject each other's keys and the schema validates nothing. Zod's parser + * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when + * *every* side rejects it — so the emitted schema has to pool them too, and folding the members + * into one object is the encoding that says so on every target. + * + * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` + * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it + * keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. + for (const key of FOLDABLE_KEYS) + if (key in json) + return; + // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) + return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten refs - inherit properties from parent schemas + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + // already processed + if (seen.ref === null) + return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; // prevent infinite recursion + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + // merge referenced schema into current + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + // older drafts can't combine $ref with other properties + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + assignProps(schema, refSchema); + } + // restore child's own properties (child wins) + assignProps(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + // For parent chain, child is a refinement - remove parent-only properties + if (isParentRef) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema[key]; + } + } + } + // When ref was extracted to $defs, remove properties that match the definition + if (refSchema.$ref && refSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { + delete schema[key]; + } + } + } + } + // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + // Ensure parent is processed first so its def has inherited properties + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + // De-duplicate with parent's definition + if (parentSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema[key]; + } + } + } + } + } + // execute overrides + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. + if (ctx.intersections.length) { + const carriers = new Map(); + for (const seen of ctx.seen.values()) { + for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json); + else + carriers.set(allOf, [json]); + } + } + for (const allOf of ctx.intersections) { + for (const json of carriers.get(allOf) ?? []) + foldIntersection(json); + } + } + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs + assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); + // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== undefined && result.id === rootMetaId) + delete result.id; + // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } + } + } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault" || + def.type === "catch") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + + + + +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids + if (format === "time" || laxFormat) { + delete json.format; + } + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns]; + if (patternList.length === 1) + json.pattern = patternList[0].source; + else if (patternList.length > 1) { + json.allOf = [ + ...patternList.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + // when both minimum and exclusiveMinimum exist, pick the more restrictive one + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + else if (typeof minimum === "number") { + json.minimum = minimum; + } + if (exMax) { + if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + else if (typeof maximum === "number") { + json.maximum = maximum; + } + if (typeof multipleOf === "number") { + // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. + if (Number.isFinite(multipleOf) && multipleOf !== 0) + json.multipleOf = Math.abs(multipleOf); + else + handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); +}; +const symbolProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); +}; +const voidProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + // an empty enum accepts nothing, same as z.never() + if (values.length === 0) { + json.not = {}; + return; + } + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // a literal with no values accepts nothing, same as z.never() + if (def.values.length === 0) { + json.not = {}; + return; + } + const vals = []; + for (const val of def.values) { + if (val === undefined) { + // a custom schema replaces the whole literal, so there is nothing left to accumulate + if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; + // otherwise do not add to vals + } + else if (typeof val === "bigint") { + if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } + else { + Object.assign(_json, file); // shared props at root + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs + } + } + else { + Object.assign(_json, file); + } +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const functionProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const mapProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); +}; +const setProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { + ...params, + path: [...params.path, "items"], + }); +}; +// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an +// absent key, but their declared input type stays required. An input JSON Schema describes the +// declared type, so resolve past them to the schema that actually carries the optionality. +// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see +// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && + handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } + json.type = "object"; + json.properties = {}; + for (const key in shape) { + // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into + assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + })); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const field = def.shape[key]; + if (ctx.io === "input") { + return inputOptin(field) === undefined; + } + else { + return field._zod.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. + ctx.intersections.push(allOf); +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; + if (!optional) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (isClosed) { + json.items = false; + } + else if (rest) { + json.items = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else { + json.items = prefixItems; + if (isClosed) { + json.additionalItems = false; + } + else if (rest) { + json.additionalItems = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + // explicit user-defined length checks take precedence + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the + * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key + * behind a wrapper only carries its own `type` before then, and a union key only has its branches. + * + * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather + * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this + * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` + * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema + * outright. */ +function stringifyKeyNames(bySchema, json, visited) { + // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. + if (json.$ref) { + // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again + if (visited.has(json)) + return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) + return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` + if (mapped.some((branch, i) => branch !== branches[i])) + json = { ...json, [keyword]: mapped }; + } + // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + // a heterogeneous key carries no type at all, so its numeric members are caught here instead + const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); + if (!numericType && !values?.some((v) => typeof v === "number")) + return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) + rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + // a heterogeneous key keeps its absent type: the stringified members already say what a key may be + if (!numericType) + return rest; + rest.type = "string"; + if (!values) + rest.pattern = (types.includes("number") ? number : integer).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = new WeakMap(); +function rewriteKeyNames(ctx) { + // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. + const bySchema = new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + // Use patternProperties for looseRecord with regex patterns + const valueSchema = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"], + }); + json.patternProperties = {}; + for (const pattern of patterns) { + assignProp(json.patternProperties, pattern.source, valueSchema); + } + } + else { + // Default behavior: use propertyNames + additionalProperties + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + // Add required for keys with discrete values (enum, literal, etc.) + const keyValues = keyType._zod.values; + // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json.required = validKeyValues.map(String); + } + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. + * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other + * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + assignProp(schemas, key, finalize(ctx, schema)); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + + +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + credit_card: "credit card number", + jwt: "JWT", + template_literal: "input", + }; + // type names: missing keys = do not translate (use raw value via ?? fallback) + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN", + // All other type names omitted - they fall back to raw values via ?? operator + }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { + return String(input); + } + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": { + const expected = getTypeName(issue.expected); + const receivedType = parsedType(issue.input); + const received = getTypeName(receivedType, issue.input); + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { + const opts = issue.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + if (issue.inclusive === false) { + return "Invalid input: more than one option matched"; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* export default */ function en() { + return { + localeError: en_error(), + }; +} + + + + +/* Prototypes that already carry the lazy helper methods. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +/* Helper methods live as non-enumerable lazy getters on the shared + * prototype instead of own properties on every instance. On first + * access the getter allocates the per-instance closure and caches it + * as a non-enumerable own property, so detached usage still works and + * the allocation only happens for methods actually touched. */ +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + }, + }); +} +const classic_errors_initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + }, + }); +}; +const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); +const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + + + +const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); +const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); +const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// Codec functions +const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); +const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); +const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); +const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); +const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + + + + + + + + +// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + core_config(en()); +} +// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + core_config({ memoizer: memoizer() }); +} +const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { + checks: [ + ...(def.checks ?? []), + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return schemas_optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return schemas_optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return schemas_array(this); + }, + or(arg) { + return schemas_union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return schemas_default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return schemas_catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(undefined).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output"), + }, + }); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, + parse: function _parse(data, params) { + return classic_parse_parse(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return parse_safeParse(this, data, params); + }, + async safeParseAsync(data, params) { + return parse_safeParseAsync(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_own(this, "spa", value); + }, + encode: function _encode(data, params) { + return classic_parse_encode(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return classic_parse_decode(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return parse_safeEncode(this, data, params); + }, + safeDecode(data, params) { + return parse_safeDecode(this, data, params); + }, + async safeEncodeAsync(data, params) { + return parse_safeEncodeAsync(this, data, params); + }, + async safeDecodeAsync(data, params) { + return parse_safeDecodeAsync(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + }, +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; +}, { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + }, +}); +const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(api_emoji(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(schemas_ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(schemas_ZodISODuration, params)); + }, +}); +function schemas_string(params) { + return _string(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_email(params) { + return _email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_guid(params) { + return core._guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_uuid(params) { + return core._uuid(ZodUUID, params); +} +function uuidv4(params) { + return core._uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return core._uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function uuidv7(params) { + return core._uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return core._url(ZodURL, { + protocol: core.regexes.httpProtocol, + hostname: core.regexes.domain, + ...util.normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_emoji(params) { + return core._emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_nanoid(params) { + return core._nanoid(ZodNanoID, params); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** + * Validates a CUID v1 string. + * + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. + * See https://github.com/paralleldrive/cuid. + */ +function schemas_cuid(params) { + return core._cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid2(params) { + return core._cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ulid(params) { + return core._ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_xid(params) { + return core._xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ksuid(params) { + return core._ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv4(params) { + return core._ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_mac(params) { + return core._mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv6(params) { + return core._ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv4(params) { + return core._cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv6(params) { + return core._cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64(params) { + return core._base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64url(params) { + return core._base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_e164(params) { + return core._e164(ZodE164, params); +} +const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { + core.$ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_creditCard(params) { + return core._creditCard(ZodCreditCard, params); +} +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return core._jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function stringFormat(format, fnOrRegex, _params = {}) { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function schemas_hostname(_params) { + return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); +} +function schemas_hex(_params) { + return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); +} +function schemas_hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = core.regexes[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return core._stringFormat(ZodCustomStringFormat, format, regex, params); +} +const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}, { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(schemas_int(params)); + }, + safe(params) { + return this.check(schemas_int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + }, +}); +function schemas_number(params) { + return _number(ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function schemas_int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return core._float32(ZodNumberFormat, params); +} +function float64(params) { + return core._float64(ZodNumberFormat, params); +} +function int32(params) { + return core._int32(ZodNumberFormat, params); +} +function uint32(params) { + return core._uint32(ZodNumberFormat, params); +} +const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function schemas_boolean(params) { + return _boolean(ZodBoolean, params); +} +const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}, { + gte(value, params) { + return this.check(checks.gte(value, params)); + }, + min(value, params) { + return this.check(checks.gte(value, params)); + }, + gt(value, params) { + return this.check(checks.gt(value, params)); + }, + lt(value, params) { + return this.check(checks.lt(value, params)); + }, + lte(value, params) { + return this.check(checks.lte(value, params)); + }, + max(value, params) { + return this.check(checks.lte(value, params)); + }, + positive(params) { + return this.check(checks.gt(BigInt(0), params)); + }, + negative(params) { + return this.check(checks.lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(checks.lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(checks.gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(checks.multipleOf(value, params)); + }, +}))); +function schemas_bigint(params) { + return core._bigint(ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}))); +function int64(params) { + return core._int64(ZodBigIntFormat, params); +} +function uint64(params) { + return core._uint64(ZodBigIntFormat, params); +} +const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); +}))); +function symbol(params) { + return core._symbol(ZodSymbol, params); +} +const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); +}))); +function schemas_undefined(params) { + return core._undefined(ZodUndefined, params); +} + +const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function schemas_null(params) { + return api_null(ZodNull, params); +} + +const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); +}); +function any() { + return _any(ZodAny); +} +const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return _never(ZodNever, params); +} +const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); +}))); +function schemas_void(params) { + return core._void(ZodVoid, params); +} + +const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}))); +function schemas_date(params) { + return core._date(ZodDate, params); +} +const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + }, +}); +function schemas_array(element, params) { + return _array(ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); +} +const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return schemas_enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall: catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: undefined }); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_required(ZodNonOptional, this, args[0]); + }, +}); +function schemas_object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params), + }; + return new ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util.normalizeParams(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params), + }); +} +const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function schemas_union(options, params) { + return new ZodUnion({ + type: "union", + options: options, + ...normalizeParams(params), + }); +} +const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}))); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options: options, + discriminator, + ...normalizeParams(params), + }); +} +const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest: rest, + }); + }, + partial() { + const def = this._zod.def; + // a refinement was authored against the full arity; partialing would run it on a shorter array + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), + }); + }, +}))); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...util.normalizeParams(params), + }); +} +const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function schemas_record(keyType, valueType, params) { + // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: schemas_string(), + valueType: keyType, + ...normalizeParams(valueType), + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...util.normalizeParams(params), + partial: true, + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...util.normalizeParams(params), + }); +} +const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; +}); +function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}))); +function schemas_file(params) { + return core._file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function schemas_optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function schemas_nullish(innerType) { + return schemas_optional(nullable(innerType)); +} +const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function schemas_default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params), + }); +} +const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function schemas_catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), + }); +} + +const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); +}))); +function nan(params) { + return core._nan(ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodCodec.init(inst, def); +}))); +function schemas_codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +function invertCodec(codec) { + const def = codec._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform, + }); +} +const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { + core.$ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); +}))); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { + core.$ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function schemas_promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { + core.$ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); +}))); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +// custom checks +function schemas_check(fn) { + const ch = new core.$ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return core._custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn, params) { + return _superRefine(fn, params); +} +// Re-export describe and meta from core +const schemas_describe = describe; +const schemas_meta = api_meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util.normalizeParams(params), + }); + inst._zod.bag.Class = cls; + // Override check to emit invalid_type instead of custom + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(inst._zod.def.path ?? [])], + }); + } + }; + return inst; +} + +// stringbool +const stringbool = (...args) => core._stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString, +}, ...args); +function schemas_json(params) { + const jsonSchema = lazy(() => { + return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema, + }); +} + + + + +function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); +} +function iso_date(params) { + return _isoDate(ZodISODate, params); +} +function iso_time(params) { + return core._isoTime(ZodISOTime, params); +} +function iso_duration(params) { + return core._isoDuration(ZodISODuration, params); +} + +// Zod 3 compat layer + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +const ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom", +}; + +/** @deprecated Use `z.config(params)` instead. */ +function setErrorMap(map) { + core.config({ + customError: map, + }); +} +/** @deprecated Use `z.config()` instead. */ +function getErrorMap() { + return core.config().customError; +} +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var compat_ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { +})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); + + + +function coerce_string(params) { + return core._coercedString(schemas.ZodString, params); +} +function coerce_number(params) { + return _coercedNumber(ZodNumber, params); +} +function coerce_boolean(params) { + return core._coercedBoolean(schemas.ZodBoolean, params); +} +function coerce_bigint(params) { + return core._coercedBigint(schemas.ZodBigInt, params); +} +function coerce_date(params) { + return core._coercedDate(schemas.ZodDate, params); +} + + + +//#region src/constants.ts +const LATEST_PROTOCOL_VERSION = "2025-11-25"; +const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +/** +* `_meta` key associating a message with a 2025-11-25 task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +/** +* `_meta` key carrying the MCP protocol version governing a request. +* +* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. +*/ +const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; +/** +* `_meta` key identifying the client software making a request. +* +* Clients SHOULD include it on every request; the value is self-reported and +* intended for display, logging, and debugging — servers should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; +/** +* `_meta` key identifying the server software producing a response. +* +* Servers SHOULD include it on every response; the value is self-reported and +* intended for display, logging, and debugging — clients should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; +/** +* `_meta` key carrying the client's capabilities for a request. +* +* Capabilities are declared per request rather than once at initialization; +* servers must not infer capabilities from prior requests. +*/ +const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; +/** +* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request +* that opened the stream a notification was delivered on. +* +* Stamped by the server on every notification delivered via a +* `subscriptions/listen` stream (including the leading +* `notifications/subscriptions/acknowledged`); on stdio, where all messages +* share one channel, clients use it to correlate notifications with their +* originating subscription. The value is the listen request's JSON-RPC ID +* verbatim. +*/ +const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; +/** +* `_meta` key carrying the desired log level for a request. +* +* When absent, the server must not send `notifications/message` notifications +* for the request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. +*/ +const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; +/** +* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `traceparent` header format, +* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. +* +* @see https://www.w3.org/TR/trace-context/#traceparent-header +*/ +const TRACEPARENT_META_KEY = "traceparent"; +/** +* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `tracestate` header format, +* e.g. `vendor1=value1,vendor2=value2`. +* +* @see https://www.w3.org/TR/trace-context/#tracestate-header +*/ +const TRACESTATE_META_KEY = "tracestate"; +/** +* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C Baggage header format, +* e.g. `userId=alice,serverRegion=us-east-1`. +* +* @see https://www.w3.org/TR/baggage/ +*/ +const BAGGAGE_META_KEY = "baggage"; +const JSONRPC_VERSION = "2.0"; +const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); +const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); +const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); +const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); +const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); + +//#endregion +//#region src/schemas.ts +const JSONValueSchema = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema), + schemas_array(JSONValueSchema) +])); +const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); +const JSONArraySchema = schemas_array(JSONValueSchema); +/** +* A progress token, used to associate progress notifications with the original request. +*/ +const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* An opaque token used to represent a cursor for pagination. +*/ +const CursorSchema = schemas_string(); +/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ +const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); +/** +* Metadata for associating messages with a task. +* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); +const RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** +* Common params for any request. +*/ +const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +/** +* Common params for any task-augmented request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); +const RequestSchema = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +const NotificationSchema = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema.loose().optional() +}); +/** +* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). +* Loose — implementation-specific keys pass through. +* +* The serverInfo key identifies the server software producing the response +* (servers SHOULD include it on every response; the value is self-reported +* and intended for display, logging, and debugging). The getter defers the +* `ImplementationSchema` reference, which is declared later in this file. +*/ +const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); +} }); +const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); +/** +* A uniquely identifying ID for a request in JSON-RPC. +*/ +const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* A request that expects a response. +*/ +const JSONRPCRequestSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +/** +* A notification which does not expect a response. +*/ +const JSONRPCNotificationSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +/** +* A successful (non-error) response to a request. +*/ +const JSONRPCResultResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +/** +* A response to a request that indicates an error occurred. +*/ +const JSONRPCErrorResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: schemas_object({ + code: schemas_number().int(), + message: schemas_string(), + data: unknown().optional() + }) +}).strict(); +const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/** +* A response that indicates success but carries no data. +*/ +const EmptyResultSchema = ResultSchema.strict(); +const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: schemas_string().optional() +}); +/** +* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. +* +* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. +* +* This notification indicates that the result will be unused, so any associated processing SHOULD cease. +* +* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. +*/ +const CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +/** +* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. +*/ +const IconSchema = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() +}); +/** +* Base schema to add `icons` property. +* +*/ +const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); +/** +* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. +*/ +const BaseMetadataSchema = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() +}); +/** +* Describes the name and version of an MCP implementation. +*/ +const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() +}); +const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); +const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; +}, intersection(schemas_object({ + form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() +}), JSONObjectSchema.optional())); +/** +* Task capabilities for clients, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() +}); +/** +* Task capabilities for servers, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() +}); +/** +* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. +*/ +const ClientCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + sampling: schemas_object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** +* This request is sent from the client to the server when it first connects, asking it to begin initialization. +*/ +const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +/** +* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. +*/ +const ServerCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +/** +* After receiving an initialize request from the client, the server sends this response. +*/ +const InitializeResultSchema = ResultSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: schemas_string().optional() +}); +/** +* This notification is sent from the client to the server after initialization has finished. +*/ +const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +/** +* A request from the client asking the server to advertise its supported protocol +* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers +* MUST implement `server/discover`. Clients MAY call it but are not required to — +* version negotiation can also happen inline via the per-request `_meta` envelope. +*/ +const DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The result returned by the server for a `server/discover` request. +*/ +const DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilitiesSchema, + instructions: schemas_string().optional() +}); +/** +* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. +*/ +const PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +const ProgressSchema = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) +}); +const ProgressNotificationParamsSchema = schemas_object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema +}); +/** +* An out-of-band notification used to inform the receiver of a progress update for a long-running request. +* +* @category notifications/progress +*/ +const ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); +const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); +/** +* The contents of a specific resource or sub-resource. +*/ +const ResourceContentsSchema = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); +/** +* A Zod schema for validating Base64 strings that is more performant and +* robust for very large inputs than the default regex-based check. It avoids +* stack overflows by using the native `atob` function for validation. +*/ +const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); +/** +* The sender or recipient of messages and data in a conversation. +*/ +const RoleSchema = schemas_enum(["user", "assistant"]); +/** +* Optional annotations providing clients additional context about a resource. +*/ +const AnnotationsSchema = schemas_object({ + audience: schemas_array(RoleSchema).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() +}); +/** +* A known resource that the server is capable of reading. +*/ +const ResourceSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* A template description for resources available on the server. +*/ +const ResourceTemplateSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of resources the server has. +*/ +const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +/** +* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. +*/ +const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); +/** +* Sent from the client to request a list of resource templates the server has. +*/ +const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +/** +* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. +*/ +const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); +const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); +/** +* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. +*/ +const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to the server, to read a specific resource URI. +*/ +const ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +/** +* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. +*/ +const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +/** +* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. +*/ +const SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +/** +* The set of notification types a client opts in to on a `subscriptions/listen` +* request. Each type is opt-in; the server MUST NOT send a notification type +* the client has not explicitly requested here. +*/ +const SubscriptionFilterSchema = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() +}); +const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent from the client to open a long-lived channel for receiving notifications +* outside the context of a specific request (protocol revision 2026-07-28). +* Replaces the previous HTTP GET endpoint and `resources/subscribe`. +*/ +const SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema +}); +const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent by the server as the first message on a `subscriptions/listen` stream +* to acknowledge that the subscription has been established and report which +* notification types it agreed to honor (protocol revision 2026-07-28). +*/ +const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); +/** +* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's +* JSON-RPC ID under the canonical subscription-id key (mirroring the same key +* on every notification delivered on the stream). Extends +* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed +* here too. +*/ +const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); +/** +* The response to a `subscriptions/listen` request, signalling that the +* subscription has ended gracefully (for example, during server shutdown). +* Because the listen stream is long-lived, this result is sent only when the +* server tears the subscription down; an abrupt transport close carries no +* response. The result body is otherwise empty. +*/ +const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); +/** +* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. +*/ +const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); +/** +* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +/** +* Describes an argument that a prompt can accept. +*/ +const PromptArgumentSchema = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) +}); +/** +* A prompt or prompt template that the server offers. +*/ +const PromptSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema)), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of prompts and prompt templates the server has. +*/ +const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +/** +* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. +*/ +const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); +/** +* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. +*/ +const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() +}); +/** +* Used by the client to get a prompt provided by the server. +*/ +const GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +/** +* Text provided to or from an LLM. +*/ +const TextContentSchema = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* An image provided to or from an LLM. +*/ +const ImageContentSchema = schemas_object({ + type: literal("image"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Audio content provided to or from an LLM. +*/ +const AudioContentSchema = schemas_object({ + type: literal("audio"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A tool call request from an assistant (LLM). +* Represents the assistant's request to use a tool. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolUseContentSchema = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* The contents of a resource, embedded into a prompt or tool call result. +*/ +const EmbeddedResourceSchema = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A resource that the server is capable of reading, included in a prompt or tool call result. +* +* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. +*/ +const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); +/** +* A content block that can be used in prompts and tool results. +*/ +const ContentBlockSchema = schemas_union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** +* Describes a message returned as part of a prompt. +*/ +const PromptMessageSchema = schemas_object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** +* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. +*/ +const GetPromptResultSchema = ResultSchema.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema) +}); +/** +* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Additional properties describing a `Tool` to clients. +* +* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. +* They are not guaranteed to provide a faithful description of +* tool behavior (including descriptive properties like `title`). +* +* Clients should never make tool use decisions based on `ToolAnnotations` +* received from untrusted servers. +*/ +const ToolAnnotationsSchema = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() +}); +/** +* Execution-related properties for a tool. +*/ +const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" +]).optional() }); +/** +* Definition for a tool the client can call. +*/ +const ToolSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the client to request a list of tools the server has. +*/ +const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +/** +* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. +*/ +const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); +/** +* The server's response to a tool call. +*/ +const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ + content: schemas_array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() +}); +/** +* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. +*/ +const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +/** +* Parameters for a `tools/call` request. +*/ +const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Used by the client to invoke a tool provided by the server. +*/ +const CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +/** +* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Base schema for list changed subscription options (without callback). +* Used internally for Zod validation of `autoRefresh` and `debounceMs`. +*/ +const ListChangedOptionsBaseSchema = schemas_object({ + autoRefresh: schemas_boolean().default(true), + debounceMs: schemas_number().int().nonnegative().default(300) +}); +/** +* The severity of a log message. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingLevelSchema = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* Parameters for a `logging/setLevel` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); +/** +* A request from the client to the server, to enable or adjust logging. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +/** +* Parameters for a `notifications/message` notification. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: schemas_string().optional(), + data: unknown() +}); +/** +* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +/** +* Hints to use for model selection. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); +/** +* The server's preferences for model selection, requested of the client during sampling. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelPreferencesSchema = schemas_object({ + hints: schemas_array(ModelHintSchema).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() +}); +/** +* Controls tool usage behavior in sampling requests. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" +]).optional() }); +/** +* The result of a tool execution, provided by the user (server). +* Represents the outcome of invoking a tool requested via `ToolUseContent`. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolResultContentSchema = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Basic content types for sampling responses (without tool use). +* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +/** +* Content block types allowed in sampling messages. +* This includes text, image, audio, tool use requests, and tool results. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** +* Describes a message issued to or received from an LLM API. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageSchema = schemas_object({ + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Parameters for a `sampling/createMessage` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + messages: schemas_array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema.optional(), + tools: schemas_array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() +}); +/** +* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +/** +* The client's response to a `sampling/create_message` request from the server. +* This is the backwards-compatible version that returns single content (no arrays). +* Used when the request does not include tools. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema, + content: SamplingContentSchema +}); +/** +* The client's response to a `sampling/create_message` request when tools were provided. +* This version supports array content for tool use flows. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) +}); +/** +* Primitive schema definition for boolean fields. +*/ +const BooleanSchemaSchema = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() +}); +/** +* Primitive schema definition for string fields. +*/ +const StringSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() +}); +/** +* Primitive schema definition for number fields. +*/ +const NumberSchemaSchema = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() +}); +/** +* Schema for single-selection enumeration without display titles for options. +*/ +const UntitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() +}); +/** +* Schema for single-selection enumeration with display titles for each option. +*/ +const TitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() +}); +/** +* Use {@linkcode TitledSingleSelectEnumSchema} instead. +* This interface will be removed in a future version. +*/ +const LegacyTitledEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() +}); +const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** +* Schema for multiple-selection enumeration without display titles for options. +*/ +const UntitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Schema for multiple-selection enumeration with display titles for each option. +*/ +const TitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Combined schema for multiple-selection enumeration +*/ +const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** +* Primitive schema definition for enum fields. +*/ +const EnumSchemaSchema = schemas_union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema +]); +/** +* Union of all primitive schema definitions. +*/ +const PrimitiveSchemaDefinitionSchema = schemas_union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +/** +* Parameters for an `elicitation/create` request for form-based elicitation. +*/ +const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) +}); +/** +* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. +*/ +const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() +}); +/** +* The parameters for a request to elicit additional information from the user via the client. +*/ +const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** +* A request from the server to elicit user input via the client. +* The client should present the message and form fields to the user (form mode) +* or navigate to a URL (URL mode). +*/ +const ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +/** +* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); +/** +* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +/** +* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. +*/ +const ElicitResultSchema = ResultSchema.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) +}); +/** +* A reference to a resource or resource template definition. +*/ +const ResourceTemplateReferenceSchema = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() +}); +/** +* Identifies a prompt. +*/ +const PromptReferenceSchema = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() +}); +/** +* Parameters for a {@linkcode CompleteRequest | completion/complete} request. +*/ +const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() +}); +/** +* A request from the client to the server, to ask for completion options. +*/ +const CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +/** +* The server's response to a {@linkcode CompleteRequest | completion/complete} request +*/ +const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) +}) }); +/** +* Represents a root directory or file that the server can operate on. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootSchema = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the server to request a list of root URIs from the client. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The client's response to a `roots/list` request from the server. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); +/** +* A notification from the client to the server, informing it that the list of roots has changed. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Task creation parameters, used to ask that the server create a task to represent a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskCreationParamsSchema = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() +}); +/** +* The status of a task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusSchema = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +/** +* A pollable state object associated with a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskSchema = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) +}); +/** +* Result returned when a task is created, containing the task data wrapped in a `task` field. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +/** +* Parameters for task status notification. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** +* A notification sent when a task's status changes. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +/** +* A request to get the state of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode GetTaskRequest | tasks/get} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* A request to get the result of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a `tasks/result` request. +* The structure matches the result type of the original request. +* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. +* +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** +* A request to list tasks. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +/** +* The response to a {@linkcode ListTasksRequest | tasks/list} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); +/** +* A request to cancel a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +const ClientRequestSchema = schemas_union([ + PingRequestSchema, + auth_CUe6YdwF_InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +const ClientNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + auth_CUe6YdwF_InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +const ClientResultSchema = schemas_union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); +const ServerRequestSchema = schemas_union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema +]); +const ServerNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +const ServerResultSchema = schemas_union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + auth_CUe6YdwF_CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); + +//#endregion +//#region src/auth.ts +/** +* Reusable URL validation that disallows `javascript:` scheme +*/ +const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url) => { + const u = new URL(url); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +/** +* RFC 9728 OAuth Protected Resource Metadata +*/ +const OAuthProtectedResourceMetadataSchema = looseObject({ + resource: schemas_string().url(), + authorization_servers: schemas_array(SafeUrlSchema).optional(), + jwks_uri: schemas_string().url().optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + bearer_methods_supported: schemas_array(schemas_string()).optional(), + resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + resource_name: schemas_string().optional(), + resource_documentation: schemas_string().optional(), + resource_policy_uri: schemas_string().url().optional(), + resource_tos_uri: schemas_string().url().optional(), + tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), + authorization_details_types_supported: schemas_array(schemas_string()).optional(), + dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + dpop_bound_access_tokens_required: schemas_boolean().optional() +}); +/** +* RFC 8414 OAuth 2.0 Authorization Server Metadata +*/ +const OAuthMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint: schemas_string().optional(), + introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + code_challenge_methods_supported: schemas_array(schemas_string()).optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery 1.0 Provider Metadata +* +* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata +*/ +const OpenIdProviderMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + acr_values_supported: schemas_array(schemas_string()).optional(), + subject_types_supported: schemas_array(schemas_string()), + id_token_signing_alg_values_supported: schemas_array(schemas_string()), + id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + display_values_supported: schemas_array(schemas_string()).optional(), + claim_types_supported: schemas_array(schemas_string()).optional(), + claims_supported: schemas_array(schemas_string()).optional(), + service_documentation: schemas_string().optional(), + claims_locales_supported: schemas_array(schemas_string()).optional(), + ui_locales_supported: schemas_array(schemas_string()).optional(), + claims_parameter_supported: schemas_boolean().optional(), + request_parameter_supported: schemas_boolean().optional(), + request_uri_parameter_supported: schemas_boolean().optional(), + require_request_uri_registration: schemas_boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery metadata that may include OAuth 2.0 fields +* This schema represents the real-world scenario where OIDC providers +* return a mix of OpenID Connect and OAuth 2.0 metadata fields +*/ +const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +/** +* OAuth 2.1 token response +*/ +const OAuthTokensSchema = schemas_object({ + access_token: schemas_string(), + id_token: schemas_string().optional(), + token_type: schemas_string(), + expires_in: coerce_number().optional(), + scope: schemas_string().optional(), + refresh_token: schemas_string().optional() +}).strip(); +/** +* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. +* +* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when +* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, +* so strict checking rejects conformant IdPs. +*/ +const IdJagTokenExchangeResponseSchema = schemas_object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: schemas_string(), + token_type: schemas_string().optional(), + expires_in: schemas_number().optional(), + scope: schemas_string().optional() +}).strip(); +/** +* OAuth 2.1 error response +*/ +const OAuthErrorResponseSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional(), + error_uri: schemas_string().optional() +}); +/** +* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` +*/ +const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata +*/ +const OAuthClientMetadataSchema = schemas_object({ + redirect_uris: schemas_array(SafeUrlSchema), + token_endpoint_auth_method: schemas_string().optional(), + grant_types: schemas_array(schemas_string()).optional(), + response_types: schemas_array(schemas_string()).optional(), + application_type: schemas_string().optional(), + client_name: schemas_string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: schemas_string().optional(), + contacts: schemas_array(schemas_string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: schemas_string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: schemas_string().optional(), + software_version: schemas_string().optional(), + software_statement: schemas_string().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration client information +*/ +const OAuthClientInformationSchema = schemas_object({ + client_id: schemas_string(), + client_secret: schemas_string().optional(), + client_id_issued_at: schemas_number().optional(), + client_secret_expires_at: schemas_number().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) +*/ +const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration error response +*/ +const OAuthClientRegistrationErrorSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional() +}).strip(); +/** +* RFC 7009 OAuth 2.0 Token Revocation request +*/ +const OAuthTokenRevocationRequestSchema = schemas_object({ + token: schemas_string(), + token_type_hint: schemas_string().optional() +}).strip(); + +//#endregion + +//# sourceMappingURL=auth-CUe6YdwF.mjs.map + + + + + + + + +//#region ../core-internal/src/errors/crossBundleBrand.ts +/** +* Cross-bundle `instanceof` support for the SDK error classes. +* +* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their +* own copy of `core-internal`, so an error constructed by one package fails a +* prototype-identity `instanceof` against the same class re-exported by the other — +* exactly the check a dual-role process (gateway, host, in-process test) writes. +* +* Instead of prototype identity, branded classes stamp every instance with the brand +* strings of its class chain under a registry symbol (`Symbol.for`, shared across +* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the +* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior +* is unchanged for anything unbranded. +* +* A class participates by defining an **own** `mcpBrand` static (via a `static {}` +* block, so nothing reaches the declaration files — a declared `protected static` +* field would make the constructor types nominally incompatible across the bundled +* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as +* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand +* keep plain prototype semantics — a foreign base-class instance never satisfies +* `instanceof UserSubclass`. +* +* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core +* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), +* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios +* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a +* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 +* (Symbol.hasInstance on every schema class for cross-version interop). +* +* Contract notes: +* - Participation criterion: **every error class exported from a public package that +* callers are documented to `instanceof` must be branded.** The per-package +* errorBrandConformance tests walk the export surfaces and fail naming any +* exported Error subclass that has not opted in. +* - Brands assert **identity, not shape**: brand strings are version-less, so an +* instance from one SDK version matches the class of another. Members added to a +* branded class in a later version may be absent on a matched instance — read +* fields defensively, and treat branded classes as additive-only. The escape +* hatch when a release must break a branded class's read contract: change that +* class's brand string in the same release, which cleanly severs cross-version +* matching for that class. The per-package brand pins make the rename +* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each +* package's errorBrandConformance test pins its package-local ones. +* - Cross-bundle matching requires **both** copies to be at or after the release +* that introduced branding; against an older copy, behavior degrades to plain +* prototype `instanceof` in both directions. +* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would +* break the brand statics; default esbuild/webpack/terser settings do not. +*/ +/** Registry symbol — identical across bundled copies and realms. */ +const BRANDS = Symbol.for("mcp.sdk.errorBrands"); +/** +* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an +* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — +* subclasses inherit the stamping without touching their constructors. +* +* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would +* satisfy `instanceof` while lacking the prototype members (getters like `.status`) +* that callers reach for after the check. +*/ +function stampErrorBrands(instance, ctor) { + const brands = /* @__PURE__ */ new Set(); + let current = ctor; + while (typeof current === "function") { + const brand = current.mcpBrand; + if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); + current = Object.getPrototypeOf(current); + } + if (brands.size === 0) return; + Object.defineProperty(instance, BRANDS, { + value: brands, + enumerable: false, + configurable: true + }); +} +/** +* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the +* value carries the **own** brand of the class being tested against (cross-bundle +* path), falling back to ordinary prototype-based `instanceof` otherwise. +*/ +function brandedHasInstance(cls, value) { + try { + if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { + const carried = value[BRANDS]; + if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; + } + } catch {} + return Function.prototype[Symbol.hasInstance].call(cls, value); +} + +//#endregion +//#region ../core-internal/src/auth/errors.ts +/** +* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} +* and extensions. +*/ +let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { + /** + * The request is missing a required parameter, includes an invalid parameter value, + * includes a parameter more than once, or is otherwise malformed. + */ + OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; + /** + * Client authentication failed (e.g., unknown client, no client authentication included, + * or unsupported authentication method). + */ + OAuthErrorCode$1["InvalidClient"] = "invalid_client"; + /** + * The provided authorization grant or refresh token is invalid, expired, revoked, + * does not match the redirection URI used in the authorization request, or was issued to another client. + */ + OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; + /** + * The authenticated client is not authorized to use this authorization grant type. + */ + OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; + /** + * The authorization grant type is not supported by the authorization server. + */ + OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; + /** + * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. + */ + OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; + /** + * The resource owner or authorization server denied the request. + */ + OAuthErrorCode$1["AccessDenied"] = "access_denied"; + /** + * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. + */ + OAuthErrorCode$1["ServerError"] = "server_error"; + /** + * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. + */ + OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; + /** + * The authorization server does not support obtaining an authorization code using this method. + */ + OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; + /** + * The authorization server does not support the requested token type. + */ + OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; + /** + * The access token provided is expired, revoked, malformed, or invalid for other reasons. + */ + OAuthErrorCode$1["InvalidToken"] = "invalid_token"; + /** + * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) + */ + OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; + /** + * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) + */ + OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; + /** + * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) + */ + OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; + /** + * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) + */ + OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; + /** + * The request requires higher privileges than provided by the access token. + */ + OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; + /** + * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) + */ + OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; + return OAuthErrorCode$1; +}({}))); +/** +* OAuth error class for all OAuth-related errors. +*/ +var src_CX2iR2pK_OAuthError = class OAuthError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, errorUri) { + super(message); + this.code = code; + this.errorUri = errorUri; + this.name = "OAuthError"; + stampErrorBrands(this, new.target); + } + /** + * Converts the error to a standard OAuth error response object. + */ + toResponseObject() { + const response = { + error: this.code, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + /** + * Creates an {@linkcode OAuthError} from an OAuth error response. + */ + static fromResponse(response) { + return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); + } +}; + +//#endregion +//#region ../core-internal/src/errors/sdkErrors.ts +/** +* Error codes for SDK errors (local errors that never cross the wire). +* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses +* descriptive string values for better developer experience. +* +* These errors are thrown locally by the SDK and are never serialized as +* JSON-RPC error responses. +*/ +let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { + /** Transport is not connected */ + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + /** Transport is already connected */ + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + /** Protocol is not initialized */ + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + /** Required capability is not supported by the remote side */ + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + /** Request timed out waiting for response */ + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + /** Connection was closed */ + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + /** Failed to send message */ + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + /** Response result failed local schema validation */ + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + /** + * The response carried a `resultType` discriminator (protocol revision + * 2026-07-28) naming a result kind this client cannot consume yet, e.g. + * `input_required`. The kind is carried in `data.resultType`. + */ + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + /** + * The multi-round-trip auto-fulfilment driver exhausted its round cap + * (`inputRequired.maxRounds`) without the server returning a complete + * result. `data.rounds` carries the cap that was hit and + * `data.lastResult` carries the last `input_required` payload received + * (`{ inputRequests, requestState? }`), so callers can inspect or resume + * the flow manually. + */ + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + /** + * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / + * `listResources()` / `listResourceTemplates()` walk hit the + * `ClientOptions.listMaxPages` cap without the server's pagination + * converging. `data.method` carries the list verb and + * `data.listMaxPages` the cap that was hit; raise the cap or fall back to + * explicit per-page `{ cursor }` calls. + */ + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + /** + * The spec method being sent does not exist on the negotiated protocol + * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or + * `server/discover` toward a 2025-era peer). Raised locally, before + * anything reaches the transport. The method and era are carried in + * `data.method` / `data.era`. + */ + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + /** + * Protocol-era negotiation at connect time failed without producing either a + * usable modern (2026-07-28+) era or a definitive legacy fallback signal — + * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a + * network failure, or the server answered the probe with a 5xx (a typed + * connect error, never an era verdict). + * + * Negotiation-phase only: this code is never used once an era is + * established. Auth walls never carry it: a 401/403 rejecting the probe + * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} + * instead, so era-recovery flows keyed on this code (e.g. cached-verdict + * gateways) can never persist a verdict for an unauthorized exchange. + */ + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + /** + * HTTP 401 authentication failure: the transport's re-auth retry still got + * 401 (`Server returned 401 after re-authentication`), or the version + * negotiation probe was rejected 401 with no `authProvider` configured + * (`Version negotiation failed: the server requires authorization (HTTP 401)`). + * Carried on an {@linkcode SdkHttpError} with `status: 401`. + */ + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + /** + * HTTP 403 denial: the step-up re-authorization retry limit was reached, + * or the version negotiation probe was rejected 403 + * (`Version negotiation failed: the server denied access (HTTP 403)`). + * Carried on an {@linkcode SdkHttpError} with `status: 403`. + */ + SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; + SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; + SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; + SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; + return SdkErrorCode$1; +}({}); +/** +* SDK errors are local errors that never cross the wire. +* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors +* that are serialized and sent as error responses. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" +* try { +* // Throwing an SDK error +* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); +* } catch (error) { +* // Checking error type by code +* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { +* // Handle timeout +* } +* } +* ``` +*/ +var src_CX2iR2pK_SdkError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } +}; +/** +* An {@linkcode SdkError} subclass for HTTP transport failures. +* +* Thrown by the streamable HTTP transport when the server responds with a +* non-OK status code. Narrows {@linkcode SdkError.data | data} to +* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status +* without unsafe casting. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" +* if (error instanceof SdkHttpError) { +* console.log(error.status); // number +* console.log(error.statusText); // string | undefined +* } +* ``` +*/ +var SdkHttpError = class extends src_CX2iR2pK_SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message, data) { + super(code, message, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } +}; + +//#endregion +//#region ../core-internal/src/shared/authUtils.ts +/** +* Utilities for handling OAuth resource URIs. +*/ +/** +* Converts a server URL to a resource URL by removing the fragment. +* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} +* states that resource URIs "MUST NOT include a fragment component". +* Keeps everything else unchanged (scheme, domain, port, path, query). +*/ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); + resourceURL.hash = ""; + return resourceURL; +} +/** +* Checks if a requested resource URL matches a configured resource URL. +* A requested resource matches if it has the same scheme, domain, port, +* and its path starts with the configured resource's path. +* +* @param options - The options object +* @param options.requestedResource - The resource URL being requested +* @param options.configuredResource - The resource URL that has been configured +* @returns true if the requested resource matches the configured resource, false otherwise +*/ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) return false; + if (requested.pathname.length < configured.pathname.length) return false; + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} + +//#endregion +//#region ../core-internal/src/shared/clientCapabilityRequirements.ts +/** +* Inbound request methods whose processing structurally requires a client +* capability, keyed by method, valued by the capabilities required. +* +* Currently empty: none of the request methods served on the 2026-07-28 +* registry unconditionally requires a client capability. Entries appear here +* when such methods exist — for example requests whose handling embeds +* elicitation or sampling input requests (the input-request engine), or +* opt-in subscription delivery. Handler-conditional requirements (a specific +* tool that needs sampling) are not expressible as a static method table and +* are enforced at the point the requirement arises instead. +*/ +const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); +/** +* The client capabilities a request method structurally requires, or +* `undefined` when the method has no static requirement. +*/ +function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { + return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; +} +function isPlainObject$7(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Whether a required nested member counts as declared even though it is not +* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at +* all) is read as form support — the pre-mode (2025) meaning of a bare +* declaration — so an `elicitation.form` requirement treats it as satisfied. +* Declaring any mode explicitly (for example `elicitation: { url: {} }`) +* removes the implication. +*/ +function isImpliedCapabilityMember(capability, member, declaredValue) { + return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; +} +/** +* The client capabilities an embedded multi-round-trip input request requires +* (call site 2 — the outbound input-request leg): a server MUST NOT send an +* `inputRequests` kind the request's declared client capabilities do not +* cover. Returns `undefined` for entries whose method is not one of the +* embedded input-request kinds (those are a server bug handled separately, +* not a capability question). +* +* The requirement is mode-aware where the capability is: URL-mode elicitation +* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires +* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a +* mode the client did not declare); sampling with `tools`/`toolChoice` +* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies +* the form requirement — see {@linkcode missingClientCapabilities}. +*/ +function requiredClientCapabilitiesForInputRequest(entry) { + switch (entry.method) { + case "elicitation/create": + if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; + return { elicitation: { form: {} } }; + case "sampling/createMessage": { + const params = entry.params; + if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; + return { sampling: {} }; + } + case "roots/list": return { roots: {} }; + default: return; + } +} +/** +* Computes the subset of `required` client capabilities the client did not +* declare. Returns `undefined` when every required capability is declared; +* otherwise returns an object in the `ClientCapabilities` shape containing +* exactly the missing capabilities (suitable for +* `data.requiredCapabilities` on the `-32021` error). +* +* A capability counts as declared when its top-level key is present on the +* declared capabilities; when the requirement names nested members (for +* example `elicitation: { url: {} }`), each named member must also be present +* under the declared capability. One lenient reading applies: a bare +* `elicitation: {}` declaration (no mode sub-capability at all) counts as +* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare +* declaration. An absent or empty `declared` value means +* nothing is declared — every required capability is missing (the structural +* clean-refusal posture for sessions with no per-request capability view). +*/ +function src_CX2iR2pK_missingClientCapabilities(required, declared) { + const missing = {}; + for (const [capability, requirement] of Object.entries(required)) { + if (requirement === void 0) continue; + const declaredValue = declared === void 0 ? void 0 : declared[capability]; + if (declaredValue === void 0) { + missing[capability] = requirement; + continue; + } + if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { + const missingMembers = {}; + for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; + if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; + } + } + return Object.keys(missing).length > 0 ? missing : void 0; +} + +//#endregion +//#region ../core-internal/src/shared/protocolEras.ts +/** +* The first protocol revision of the modern (2026-07-28) era. Revision identifiers +* are ISO dates, so lexicographic comparison orders them chronologically. +*/ +const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; +/** +* Modern-era protocol revisions this SDK can negotiate via `server/discover`. +* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy +* `initialize` list), so adding a revision here can never leak a modern version +* string into a 2025-era handshake. Internal — not part of the public API surface. +*/ +const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); +/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ +function isModernProtocolVersion(version) { + return version >= FIRST_MODERN_PROTOCOL_VERSION; +} +/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ +function legacyProtocolVersions(versions) { + return versions.filter((version) => !isModernProtocolVersion(version)); +} +/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ +function modernProtocolVersions(versions) { + return versions.filter((version) => isModernProtocolVersion(version)); +} + +//#endregion +//#region ../core-internal/src/wire/textFallback.ts +/** +* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH +* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` +* is a non-object value (array/primitive/`null`) and the handler authored no +* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. +* Object-shaped (or absent) `structuredContent` returns the same reference. +* +* Leaf module: imported by both era codec modules, so it must NOT import from +* `./codec.js` (which value-imports the rev codecs at top level — that would +* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec +* module first). +*/ +function appendTextFallbackForNonObject(result) { + const sc = result.structuredContent; + if (sc === void 0) return result; + if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; + if (result.content?.some((c) => c.type === "text") ?? false) return result; + return { + ...result, + content: [...result.content ?? [], { + type: "text", + text: JSON.stringify(sc) + }] + }; +} + +//#endregion +//#region ../core-internal/src/wire/resultFamilies.ts +/** +* Result-family keys that must never default into a `{content: []}` tools/call +* success. Shared by the 2025 wire-seam schema and server normalization. +* Leaf module (like `textFallback.ts`): imported by registry/server paths, so +* it must NOT import from `./codec.js` — that would close a runtime cycle. +*/ +const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" +]; +/** +* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and +* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. +*/ +function normalizeContentlessToolResult(value) { + if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; + return { + ...value, + content: [] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts +/** +* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from +* the public/neutral types/schemas.ts. The neutral layer is the public-API +* superset and is free to evolve (e.g., SEP-2106 widening); this file is the +* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. +* +* This is the era's complete frozen wire-parse contract — both the 2025-only +* delta (the deprecated task family, the era role unions) AND frozen copies of +* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, +* prompts/resources/completion/elicitation, …). The 2026-era codec +* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. +* +* The 2025-only delta (the task message surface, restored types-only by #2248 +* for interop with task-capable 2025 peers) is parsed ONLY through this era's +* registry; the deprecated Task* schemas also live (marked `@deprecated`) in +* the neutral schema layer so the public types stay nameable without a +* cross-layer import — nameability is constant, runtime availability is +* version-keyed — but appear in no API signature. Q1 increment 2 — deletions +* are physical: the +* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do +* carry the deprecated Task* sub-schemas by composition — soft contamination, +* tracked for anchor-exactness adjudication). +* +* The only cross-layer dependency is `import type { JSONObject, JSONValue }` +* from the neutral types barrel — pure structural type aliases with no parse +* behavior. No runtime schema is shared with the neutral layer. +*/ +function build$1() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + /** + * Common params for any request. + */ + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** + * Common params for any task-augmented request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * A response that indicates success but carries no data. + */ + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: schemas_string().optional() + }); + /** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. + */ + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + /** + * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. + */ + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + /** + * Base schema to add `icons` property. + * + */ + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + /** + * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. + */ + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + /** + * Describes the name and version of an MCP implementation. + */ + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** + * Task capabilities for clients, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** + * Task capabilities for servers, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + /** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + /** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + /** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + /** + * After receiving an initialize request from the client, the server sends this response. + */ + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: schemas_string().optional() + }); + /** + * This notification is sent from the client to the server after initialization has finished. + */ + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + /** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); + const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); + const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); + /** + * The contents of a specific resource or sub-resource. + */ + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * Optional annotations providing clients additional context about a resource. + */ + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + /** + * A known resource that the server is capable of reading. + */ + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * A template description for resources available on the server. + */ + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of resources the server has. + */ + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + /** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); + /** + * Sent from the client to request a list of resource templates the server has. + */ + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + /** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); + /** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to the server, to read a specific resource URI. + */ + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + /** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + /** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + /** + * Describes an argument that a prompt can accept. + */ + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + /** + * A prompt or prompt template that the server offers. + */ + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + /** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); + /** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }); + /** + * Used by the client to get a prompt provided by the server. + */ + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + /** + * Text provided to or from an LLM. + */ + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * An image provided to or from an LLM. + */ + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Audio content provided to or from an LLM. + */ + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * The contents of a resource, embedded into a prompt or tool call result. + */ + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. + */ + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + /** + * A content block that can be used in prompts and tool results. + */ + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + /** + * Describes a message returned as part of a prompt. + */ + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + /** + * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. + */ + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + /** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Additional properties describing a `Tool` to clients. + * + * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on `ToolAnnotations` + * received from untrusted servers. + */ + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + /** + * Execution-related properties for a tool. + */ + const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + /** + * Definition for a tool the client can call. + */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the client to request a list of tools the server has. + */ + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); + /** + * The server's response to a tool call. + */ + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_record(schemas_string(), unknown()).optional(), + isError: schemas_boolean().optional() + }); + /** + * Parameters for a `tools/call` request. + */ + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Used by the client to invoke a tool provided by the server. + */ + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + /** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * The severity of a log message. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * Parameters for a `logging/setLevel` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + /** + * A request from the client to the server, to enable or adjust logging. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + /** + * Parameters for a `notifications/message` notification. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + /** + * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + /** + * Hints to use for model selection. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + /** + * Controls tool usage behavior in sampling requests. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + /** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via `ToolUseContent`. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_object({}).loose().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + /** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** + * Describes a message issued to or received from an LLM API. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Parameters for a `sampling/createMessage` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request when tools were provided. + * This version supports array content for tool use flows. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) + }); + /** + * Primitive schema definition for boolean fields. + */ + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + /** + * Primitive schema definition for string fields. + */ + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + /** + * Primitive schema definition for number fields. + */ + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + /** + * Schema for single-selection enumeration without display titles for options. + */ + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + /** + * Schema for single-selection enumeration with display titles for each option. + */ + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + /** + * Use {@linkcode TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + */ + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + /** + * Schema for multiple-selection enumeration without display titles for options. + */ + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Schema for multiple-selection enumeration with display titles for each option. + */ + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Combined schema for multiple-selection enumeration + */ + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + /** + * Primitive schema definition for enum fields. + */ + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + /** + * Union of all primitive schema definitions. + */ + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + /** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + /** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() + }); + /** + * The parameters for a request to elicit additional information from the user via the client. + */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); + /** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + /** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) + }); + /** + * A reference to a resource or resource template definition. + */ + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + /** + * Identifies a prompt. + */ + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + /** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }); + /** + * A request from the client to the server, to ask for completion options. + */ + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) + }) }); + /** + * Represents a root directory or file that the server can operate on. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the server to request a list of root URIs from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + /** + * The client's response to a `roots/list` request from the server. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); + /** + * A notification from the client to the server, informing it that the list of roots has changed. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Task creation parameters, used to ask that the server create a task to represent a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskCreationParamsSchema$1 = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() + }); + /** + * The status of a task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusSchema$1 = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + /** + * A pollable state object associated with a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskSchema$1 = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema$1, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) + }); + /** + * Result returned when a task is created, containing the task data wrapped in a `task` field. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + /** + * Parameters for task status notification. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + /** + * A notification sent when a task's status changes. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + /** + * A request to get the state of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a {@linkcode GetTaskRequest | tasks/get} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + /** + * A request to get the result of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a `tasks/result` request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. + * + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + /** + * A request to list tasks. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + /** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); + /** + * A request to cancel a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + RequestSchema: RequestSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + ResultSchema: ResultSchema$1, + RequestIdSchema: RequestIdSchema$1, + EmptyResultSchema: EmptyResultSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, + InitializeRequestSchema: InitializeRequestSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + InitializeResultSchema: InitializeResultSchema$1, + InitializedNotificationSchema: InitializedNotificationSchema$1, + PingRequestSchema: PingRequestSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, + PaginatedRequestSchema: PaginatedRequestSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + RoleSchema: RoleSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, + ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, + SubscribeRequestSchema: SubscribeRequestSchema$1, + UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, + UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolExecutionSchema: ToolExecutionSchema$1, + ToolSchema: ToolSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, + CallToolRequestSchema: CallToolRequestSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, + SetLevelRequestSchema: SetLevelRequestSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingContentSchema: SamplingContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, + ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + RootSchema: RootSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, + TaskCreationParamsSchema: TaskCreationParamsSchema$1, + TaskStatusSchema: TaskStatusSchema$1, + TaskSchema: TaskSchema$1, + CreateTaskResultSchema: CreateTaskResultSchema$1, + TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, + TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, + GetTaskRequestSchema: GetTaskRequestSchema$1, + GetTaskResultSchema: GetTaskResultSchema$1, + GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, + GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, + ListTasksRequestSchema: ListTasksRequestSchema$1, + ListTasksResultSchema: ListTasksResultSchema$1, + CancelTaskRequestSchema: CancelTaskRequestSchema$1, + CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), + ClientRequestSchema: schemas_union([ + PingRequestSchema$1, + InitializeRequestSchema$1, + CompleteRequestSchema$1, + SetLevelRequestSchema$1, + GetPromptRequestSchema$1, + ListPromptsRequestSchema$1, + ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema$1, + SubscribeRequestSchema$1, + UnsubscribeRequestSchema$1, + CallToolRequestSchema$1, + ListToolsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ClientNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: schemas_union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: schemas_union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: schemas_union([ + EmptyResultSchema$1, + InitializeResultSchema$1, + CompleteResultSchema$1, + GetPromptResultSchema$1, + ListPromptsResultSchema$1, + ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema$1, + CallToolResultSchema$1, + ListToolsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + CallToolResultWireSchema: unknown().superRefine((value, ctx) => { + if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { + ctx.addIssue({ + code: "custom", + message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +let memo$1; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2025() { + return memo$1 ??= build$1(); +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts +/** +* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). +* +* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON +* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, +* so when an era-blind handler advertises a non-object root, the 2025 codec's +* `encodeResult('tools/list', …)` projects it down to +* `{type:'object', properties:{result:}, required:['result']}`, and +* `projectCallToolResult` wraps the matching `structuredContent` as +* `{result:}`. The 2026 codec's projections are the identity. +* +* These helpers are wire-layer property — they exist so the projection can +* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} +* and never be re-derived in shared/ or server-side code. +*/ +/** +* Whether a JSON Schema's root is non-object: either an explicit non-object +* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless +* roots that the schema-conversion layer can prove are objects are stamped +* `type:'object'` upstream, so they reach this predicate as object roots. +*/ +function isNonObjectJsonSchemaRoot(json) { + return json["type"] !== "object"; +} +/** +* Keyword-position keys whose values are instance data (not subschemas). A +* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to +* rewrite. Only consulted when the current object is in keyword position — +* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name +* position whose value IS a subschema and is recursed into. +*/ +const REF_REWRITE_DATA_POSITION_KEYS = new Set([ + "const", + "enum", + "default", + "examples" +]); +/** +* Keyword-position keys whose value is a name→subschema map. Entries inside +* such a map are in NAME position: their keys are author-chosen property +* names (which may collide with JSON Schema keywords), their values are +* subschemas to recurse into. +*/ +const REF_REWRITE_NAME_MAP_KEYS = new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies" +]); +/** +* Whether a subtree's `$id` establishes a new resolution base. A fragment-only +* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not +* change the RFC 3986 base URI — same-document pointers inside still resolve +* against the document root and must be rewritten. +*/ +function establishesNewBase(id) { + return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); +} +/** +* Wrap a non-object output schema in the 2025-era envelope: +* `{type:'object', properties:{result:}, required:['result']}`. +* +* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema +* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) +* are rewritten to account for the new `#/properties/result` root: bare `#` → +* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs +* (anything not starting with `#`) are left untouched. +* +* The rewrite is position-aware: data-valued keywords +* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended +* into; the same names appearing as property names under +* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ +* `dependencies` ARE descended into (they're subschemas). The rewrite is also +* `$id`-scoped: if the natural root carries a base-establishing `$id` no +* pointer is rewritten (same-document refs inside resolve against the embedded +* `$id` base, not the wrapper root), and any subtree that establishes its own +* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, +* draft-07's anchor spelling) does not establish a base and IS descended into. +*/ +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (establishesNewBase(natural["$id"])) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; + const rewriteRefs = (node, parentIsNameMap) => { + if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); + if (node === null || typeof node !== "object") return node; + if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; + const out = {}; + let convertedRecursion = false; + for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); + else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; + else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; + else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; + else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); + else out[k] = rewriteRefs(v, false); + if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; + else out["$ref"] = "#/properties/result"; + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/registry.ts +const requestMethodKeys$1 = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "tasks/get": null, + "tasks/result": null, + "tasks/list": null, + "tasks/cancel": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +const notificationMethodKeys$1 = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/initialized": null, + "notifications/roots/list_changed": null, + "notifications/tasks/status": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/elicitation/complete": null +}; +const resultMethodKeys = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +let maps$1; +function registryMaps() { + if (maps$1) return maps$1; + const s = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + "completion/complete": s.CompleteRequestSchema, + "logging/setLevel": s.SetLevelRequestSchema, + "prompts/get": s.GetPromptRequestSchema, + "prompts/list": s.ListPromptsRequestSchema, + "resources/list": s.ListResourcesRequestSchema, + "resources/templates/list": s.ListResourceTemplatesRequestSchema, + "resources/read": s.ReadResourceRequestSchema, + "resources/subscribe": s.SubscribeRequestSchema, + "resources/unsubscribe": s.UnsubscribeRequestSchema, + "tools/call": s.CallToolRequestSchema, + "tools/list": s.ListToolsRequestSchema, + "tasks/get": s.GetTaskRequestSchema, + "tasks/result": s.GetTaskPayloadRequestSchema, + "tasks/list": s.ListTasksRequestSchema, + "tasks/cancel": s.CancelTaskRequestSchema, + "sampling/createMessage": s.CreateMessageRequestSchema, + "elicitation/create": s.ElicitRequestSchema, + "roots/list": s.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s.CancelledNotificationSchema, + "notifications/progress": s.ProgressNotificationSchema, + "notifications/initialized": s.InitializedNotificationSchema, + "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, + "notifications/tasks/status": s.TaskStatusNotificationSchema, + "notifications/message": s.LoggingMessageNotificationSchema, + "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + "completion/complete": s.CompleteResultSchema, + "logging/setLevel": s.EmptyResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "resources/subscribe": s.EmptyResultSchema, + "resources/unsubscribe": s.EmptyResultSchema, + "tools/call": s.CallToolResultWireSchema, + "tools/list": s.ListToolsResultSchema, + "sampling/createMessage": s.CreateMessageResultWithToolsSchema, + "elicitation/create": s.ElicitResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps$1; +} +/** +* Forces the lazy registry maps (and, through them, the era's schema memo). +* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmRegistryMaps2025() { + registryMaps(); +} +/** The 2025-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +/** The 2025-era notification-method set. */ +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ +function hasResultMethod(method) { + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); +} +function getResultSchema(method) { + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; +} +function getRequestSchema(method) { + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; +} +function getNotificationSchema(method) { + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2025RequestMethods = Object.keys(requestMethodKeys$1); +const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/codec.ts +function isPlainObject$6(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState$1(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" +}; +/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ +function toolNeedsLegacyWrap(t) { + return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ +function toNeutralResult(value) { + return value; +} +const rev2025Codec = { + era: "2025-11-25", + hasRequestMethod: hasRequestMethod2025, + hasNotificationMethod: hasNotificationMethod2025, + validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), + validateResult: (method, raw) => triState$1(getResultSchema(method), raw), + validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), + hasInputRequestMethod: () => false, + validateInputRequest: () => NOT_IN_ERA$1, + validateInputResponse: () => NOT_IN_ERA$1, + samplingResultVariant: ((hasTools, raw) => { + const s = buildSchemas2025(); + return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }), + outboundEnvelope: (_material) => void 0, + validateEnvelopeMeta: (_meta) => [], + projectCallToolResult(result, advertisedOutputSchema) { + const withText = appendTextFallbackForNonObject(result); + const sc = withText.structuredContent; + if (sc === void 0) return withText; + const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); + const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); + if (!valueIsNonObject && !schemaWrapped) return withText; + return { + ...withText, + structuredContent: { result: sc } + }; + }, + decodeResult(_method, raw) { + if (isPlainObject$6(raw) && "resultType" in raw) { + const stripped = { ...raw }; + delete stripped["resultType"]; + return { + kind: "complete", + result: toNeutralResult(stripped) + }; + } + return { + kind: "complete", + result: toNeutralResult(raw) + }; + }, + encodeResult(method, result) { + if (method !== "tools/list") return result; + const tools = result.tools; + if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; + return { + ...result, + tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { + ...t, + outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) + } : t) + }; + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope: (_material) => void 0 +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts +/** +* 2026-era wire schemas (protocol revision 2026-07-28). +* +* Fully self-contained — no runtime imports from types/schemas.ts. The +* neutral types/schemas.ts layer is the public-API superset and is free to +* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN +* against the 2026-07-28 anchor. Every era-shared building block (content +* blocks, resources, prompts, capabilities, notifications, …) that the wire +* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at +* the point this revision was sealed, dependencies first. The only cross-layer +* dependency is `import type { JSONObject, JSONValue }` from the neutral types +* barrel — pure structural type aliases with no parse behavior. +* +* This module is the only place the per-request `_meta` envelope is modeled. +* The envelope is wire-only vocabulary: the protocol layer lifts it off +* inbound requests before any handler runs and surfaces it at +* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at +* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc +* deferral ("enforced per request at dispatch time, not here") is now +* discharged by that codec step. +* +* No 2025-era traffic ever touches this module, so requiredness here is +* bare and spec-exact (the shared-schema `.catch` hazards do not apply). +* +* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed +* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the +* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from +* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result +* body to the new `ResultMetaObject` key +* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). +* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is +* modeled anywhere (per ruling: the final revision is the only 2026-07-28). +*/ +function build() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * The severity of a log message. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = schemas_object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = schemas_object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + /** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28: the protocol version governing the request, the client implementation + * info, and the client's capabilities — declared per request rather than once at + * initialization — plus the optional log-level opt-in. + * + * This schema models the complete envelope on its own (loose: foreign keys + * pass through - the lift extracts exactly the reserved keys, so enforcement + * never sees extension material). Requiredness is enforced per request at + * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + */ + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: looseObject({ + $schema: schemas_string().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string(), + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era sampling content union (composes the forked tool-result shape). */ + const SamplingMessageContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** 2026-era SamplingMessage (anchor-exact: single block or array). */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** Open union per the anchor: 'complete' | 'input_required' | string. */ + const ResultTypeSchema = schemas_string(); + /** + * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): + * loose, with the serverInfo key typed when present; the outbound stamp + * is the encode contract's `stampServerInfoMeta` step. + */ + const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); + const wireMeta = ResultMetaSchema.optional(); + function wireResult(shape) { + return looseObject({ + _meta: wireMeta, + resultType: ResultTypeSchema.default("complete"), + ...shape + }); + } + const ResultSchema$1 = wireResult({}); + const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); + const CallToolResultSchema$1 = wireResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }); + const ListToolsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }); + /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ + const CacheableResultSchema = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }); + /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ + const CreateMessageRequestParamsSchema$1 = schemas_object({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** 2026-era embedded sampling request (de-JSON-RPC'd). */ + const CreateMessageRequestSchema$1 = schemas_object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input + * requests do NOT carry the per-request `_meta` envelope on this revision — + * the anchor declares a bare optional `_meta` on `params`. + */ + const ListRootsRequestSchema$1 = schemas_object({ + method: literal("roots/list"), + params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() + }); + /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ + const CreateMessageResultSchema$1 = schemas_object({ + ...SamplingMessageSchema$1.shape, + model: schemas_string(), + stopReason: schemas_string().optional() + }); + /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ + const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); + /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ + const ElicitResultSchema$1 = schemas_object({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional() + }); + /** + * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed + * `elicitationId` (and the `notifications/elicitation/complete` channel it + * keyed) — the shared schema keeps the field because it is required on the + * frozen 2025-11-25 revision. + */ + const ElicitRequestURLParamsSchema$1 = schemas_object({ + mode: literal("url"), + message: schemas_string(), + url: schemas_string().url() + }); + /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ + const ElicitRequestSchema$1 = schemas_object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** A single embedded input request (one of the three demoted server→client requests). */ + const InputRequestSchema = schemas_union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ + const InputResponseSchema = schemas_union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + /** Map of embedded input requests, keyed by server-assigned identifiers. */ + const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); + /** Map of embedded input responses, keyed by the corresponding request identifiers. */ + const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); + /** + * The wire InputRequiredResult: `resultType: 'input_required'` plus at least + * one of `inputRequests` / `requestState` (the at-least-one rule is enforced + * at the server seam, not by this parse shape). + */ + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: schemas_string().optional() + }); + /** The retry-channel members carried by client-initiated requests on this revision. */ + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: schemas_string().optional() + }; + /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ + const InputResponseRequestParamsSchema = schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + /** Post-lift request `_meta` (progressToken + extension keys; loose). */ + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional(), + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; + const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); + const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); + const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); + const GetPromptRequestSchema$1 = wireRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: schemas_string(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + /** Anchor SubscriptionFilter (2026-only). */ + const SubscriptionFilterSchema$1 = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + /** + * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on + * the graceful-close result. Extends `ResultMetaObject` since spec PR + * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). + */ + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + /** + * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` + * response signalling that the subscription has ended gracefully (server + * shutdown). An abrupt transport close carries no response — the client treats + * stream-close-without-result as a disconnect. + */ + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }), + "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), + "resources/list": dispatchRequest("resources/list", paginatedParamsShape), + "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), + "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + /** Dispatch (post-lift) result schemas, keyed by method — what the funnel + * validates AFTER `decodeResult` consumed `resultType`. */ + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }), + "tools/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + /** + * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the + * subscriptions/listen demux key typed when present. Only the anchor-exact + * SHAPE is modeled here — listen delivery itself (filter gating, demux, + * teardown) is #14 scope and not implemented by this module. + */ + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ + const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ + method: literal("notifications/subscriptions/acknowledged"), + params: schemas_object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + /** + * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` + * is REQUIRED on this revision — the shared schema keeps it optional because + * the frozen 2025-11-25 shape declares it optional (task cancellation goes + * through `tasks/cancel` there). Requiredness is bare because no 2025-era + * traffic touches this module. + */ + const CancelledNotificationParamsSchema$1 = schemas_object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: schemas_string().optional() + }); + /** 2026-era `notifications/cancelled` (see the params fork above). */ + const CancelledNotificationSchema$1 = schemas_object({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const notificationSchemas2026 = { + "notifications/cancelled": CancelledNotificationSchema$1, + "notifications/progress": ProgressNotificationSchema$1, + "notifications/message": LoggingMessageNotificationSchema$1, + "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, + "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, + "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, + "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, + "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 + }; + const wireResultResponse = (result) => schemas_object({ + jsonrpc: literal("2.0"), + id: schemas_union([schemas_string(), schemas_number().int()]), + result + }).strict(); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + RequestIdSchema: RequestIdSchema$1, + RoleSchema: RoleSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + RootSchema: RootSchema$1, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema: ToolSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + ResultTypeSchema, + ResultMetaSchema, + ResultSchema: ResultSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + CacheableResultSchema, + DiscoverResultSchema: DiscoverResultSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema: CallToolRequestSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + DiscoverRequestSchema: DiscoverRequestSchema$1, + SubscriptionFilterSchema: SubscriptionFilterSchema$1, + SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, + SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, + SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + notificationSchemas2026, + JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), + CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +let src_CX2iR2pK_memo; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2026() { + return src_CX2iR2pK_memo ??= build(); +} + +//#endregion +//#region ../core-internal/src/shared/resultCacheHints.ts +/** +* The operations whose results are cacheable on the 2026-07-28 revision (the +* `CacheableResult` extenders). This list is closed: no other operation's +* result ever receives cache fields from the SDK. +*/ +const CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" +]; +/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +/** +* The symbol-keyed carrier for a configured cache hint on a result object. +* Symbol properties are invisible to JSON serialization, so the carrier can be +* attached era-blind: only the 2026-era encode seam consumes it. +*/ +const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); +/** +* Attaches a configured cache hint to a result as the encode-time fallback. +* Returns the result unchanged when there is nothing to attach. When a more +* specific hint is already attached, the two hints are combined per field +* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the +* per-registration hint attached by the feature layer keeps every field it +* sets, and the server-level per-operation hint only fills the fields the +* more specific hint leaves unset. +*/ +function attachCacheHintFallback(result, hint) { + if (hint === void 0) return result; + const attached = result[RESULT_CACHE_HINT_FALLBACK]; + if (attached === void 0) return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: hint + }; + const merged = {}; + const ttlMs = attached.ttlMs ?? hint.ttlMs; + if (ttlMs !== void 0) merged.ttlMs = ttlMs; + const cacheScope = attached.cacheScope ?? hint.cacheScope; + if (cacheScope !== void 0) merged.cacheScope = cacheScope; + return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: merged + }; +} +/** Reads the configured cache-hint fallback attached to a result, if any. */ +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +/** +* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe +* integers are required because the wire schemas validate `ttlMs` as an +* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value +* outside that range is treated as invalid here so it falls through to the +* next author instead of being emitted and rejected downstream. +*/ +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +/** Whether a value is a valid `cacheScope`. */ +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +/** +* Validates a configured cache hint at configuration time. Throws a +* `RangeError` naming the offending field, so misconfiguration fails at +* startup/registration rather than silently degrading at encode time. +*/ +function assertValidCacheHint(hint, context) { + if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); + if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); +} + +//#endregion +//#region ../core-internal/src/types/enums.ts +/** +* Error codes for protocol errors that cross the wire as JSON-RPC error responses. +* These follow the JSON-RPC specification and MCP-specific extensions. +*/ +let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { + ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; + /** + * Resource not found. + * + * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` + * misses answer `-32602` (Invalid Params) on every protocol revision per + * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to + * `-32602` at the era encode seam. The member stays importable so clients + * can recognise `-32002` from peers built on earlier SDK releases (the + * spec's "clients SHOULD also accept `-32002`" backwards-compatibility + * clause). Throw `ResourceNotFoundError` instead. + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + /** + * Processing the request requires a capability the client did not declare + * in the request's `clientCapabilities` (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + /** + * The request's protocol version is unknown to the server or unsupported + * by it (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; +}({}); + +//#endregion +//#region ../core-internal/src/types/errors.ts +/** +* Protocol errors are JSON-RPC errors that cross the wire as error responses. +* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. +* +* `instanceof` on this class (and its subclasses) is brand-matched, so it works +* across separately bundled copies of the SDK — e.g. an error constructed by +* `@modelcontextprotocol/client` matches the class re-exported by +* `@modelcontextprotocol/server` in the same process. +*/ +var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "ProtocolError"; + stampErrorBrands(this, new.target); + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); + } + return new ProtocolError(code, message, data); + } +}; +/** +* Error type for a `resources/read` miss: the requested resource does not +* exist. The wire code is `-32602` (Invalid Params) on every protocol +* revision — the spec MUST for revision 2026-07-28, and the value the v1.x +* SDK has always emitted on earlier revisions. The error data echoes the +* requested URI. +* +* Recognise this error by checking `error.data` is exactly `{ uri: string }` +* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; +* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also +* accept `-32002` as resource not found — earlier SDK builds emitted that +* code, and {@linkcode ProtocolError.fromError} reconstructs this class for +* either code **when `error.data` carries `uri`** (a bare `-32002` without +* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks +* are brand-matched and work across separately bundled copies of the SDK. +*/ +var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message = `Resource not found: ${uri}`) { + super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } +}; +/** +* Specialized error type when a tool requires a URL mode elicitation. +* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. +*/ +var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +/** +* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol +* revision 2026-07-28): the request's protocol version is unknown to the server or +* unsupported by it. +* +* The error data lists the protocol versions the receiver supports (`supported`), +* so the sender can choose a mutually supported version and retry, and echoes the +* version that was requested (`requested`). +*/ +var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message = `Unsupported protocol version: ${data.requested}`) { + super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } +}; +/** +* Error type for the `-32021` MissingRequiredClientCapability protocol error +* (protocol revision 2026-07-28): processing the request requires a capability +* the client did not declare in the request's `clientCapabilities`. +* +* The error data lists the missing capabilities (`requiredCapabilities`) in +* the `ClientCapabilities` shape, so the client can see exactly what it would +* have to declare for the request to be served. On HTTP, the response status +* is `400 Bad Request`. +* +* Recognize this error by its code and `data.requiredCapabilities`, or by +* `instanceof` — checks are brand-matched and work across separately bundled +* copies of the SDK. +*/ +var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); + } + /** + * The capabilities the server requires from the client to process the + * request (only the missing capabilities are listed). + */ + get requiredCapabilities() { + return this.data.requiredCapabilities; + } +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts +/** The default cache policy when neither the handler nor configuration provides one. */ +const DEFAULT_CACHE_TTL_MS = 0; +const DEFAULT_CACHE_SCOPE = "private"; +/** +* Request methods whose spec result vocabulary goes beyond `'complete'` on the +* 2026-07-28 revision: their results may be `input_required` (multi +* round-trip requests), so a handler-provided `resultType` passes through the +* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits +* a JSON-RPC result — termination is stream close (HTTP) or +* `notifications/cancelled` (stdio) per the spec. +*/ +const EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" +]; +/** +* Step 1 of the encode contract: ensure the outbound result carries the +* required `resultType` discriminator. +* +* - No handler-provided value → stamp `'complete'`. +* - Handler-provided `'complete'` → kept as-is. +* - Handler-provided non-`'complete'` value on a method whose vocabulary +* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. +* The value is forwarded verbatim — the wire vocabulary is an open union and +* the SDK does not validate the string, so emitting a `resultType` the +* negotiated revision does not define is the handler author's +* responsibility. +* - Handler-provided non-`'complete'` value on any other method → internal +* error (loud): the value would be mis-typed on the wire, and silently +* rewriting it would hide a server bug. +*/ +function stampResultType(method, result) { + const provided = result["resultType"]; + if (provided === void 0) return { + ...result, + resultType: "complete" + }; + if (provided === "complete") return result; + if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +/** +* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields +* on cacheable results. +* +* Applies only when the (post-stamp) `resultType` is `'complete'` and the +* method is one of the cacheable operations; everything else is returned +* untouched apart from removing the configured-hint carrier. Field resolution +* is per field, most specific author first: a valid handler-returned value, +* then the configured cache hint attached by the server layer, then the +* defaults. Handler-returned values are validated at encode time (`ttlMs` +* must be a non-negative integer, `cacheScope` must be `'public'` or +* `'private'`); invalid values are ignored rather than emitted. +*/ +function fillCacheFields(method, result) { + const fallback = cacheHintFallbackOf(result); + if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); + const provided = result; + const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); + const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); + const filled = { + ...provided, + ttlMs, + cacheScope + }; + delete filled[RESULT_CACHE_HINT_FALLBACK]; + return filled; +} +function isPlainObject$5(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Step 3 of the encode contract: stamp the server's identity into the +* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: +* servers SHOULD include it on every response). +* +* - No `serverInfo` supplied (a client instance, or a hand-constructed +* protocol object) → identity function. +* - The result's `_meta` already carries the key → kept as-is (the handler +* is the more specific author; mirrors the cache-fill resolution order). +* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: +* the stamp never rewrites handler material, and the malformed value fails +* loudly at the peer instead of being silently replaced here. +* - Otherwise → the key is added, preserving any other `_meta` entries. +* +* Runs for every result regardless of `resultType`: the anchor types +* `Result._meta` as `ResultMetaObject` on all results, `input_required` +* included. +*/ +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta = result["_meta"]; + if (meta === void 0) return { + ...result, + _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$5(meta)) return result; + if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta, + [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo + } + }; +} +function resolveTtlMs(fallback) { + return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; +} +function resolveCacheScope(fallback) { + return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; +} +function stripCacheHintFallback(result) { + const copy = { ...result }; + delete copy[RESULT_CACHE_HINT_FALLBACK]; + return copy; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts +/** +* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 +* multi round-trip requests), dispatch view. +* +* The three former server→client wire requests (`elicitation/create`, +* `sampling/createMessage`, `roots/list`) are NOT wire request methods on +* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an +* `input_required` result. The multi-round-trip driver dispatches those +* embedded payloads to the client's registered handlers through the normal +* handler machinery, and these are the schemas that dispatch parses them +* with: lenient where the anchor's wire-true artifacts are strict (an +* embedded request never carries the per-request `_meta` envelope), exact +* where the vocabulary forks (the sampling shapes compose the forked +* SamplingMessage/Tool payloads). +* +* Registry membership is intentionally NOT granted here — these methods stay +* absent from the 2026-era request registry (a peer sending one as a wire +* request still gets −32601 by absence). Only the codec's +* `inputRequestSchema`/`inputResponseSchema` accessors expose them. +*/ +/** The embedded input-request methods of the 2026-07-28 revision. */ +const INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" +]; +let maps; +function inputSchemaMaps() { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + "elicitation/create": schemas_object({ + method: literal("elicitation/create"), + params: s.ElicitRequestParamsSchema + }), + "sampling/createMessage": schemas_object({ + method: literal("sampling/createMessage"), + params: s.CreateMessageRequestParamsSchema + }), + "roots/list": schemas_object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s.ElicitResultSchema, + "sampling/createMessage": s.CreateMessageResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps; +} +/** +* Forces the lazy embedded-request maps (and, through them, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmInputSchemaMaps2026() { + inputSchemaMaps(); +} +function isInputRequestMethod2026(method) { + return INPUT_REQUEST_METHODS_2026.includes(method); +} +function getInputRequestSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; +} +function getInputResponseSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/registry.ts +const requestMethodKeys = { + "tools/call": null, + "tools/list": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "completion/complete": null, + "server/discover": null, + "subscriptions/listen": null +}; +const notificationMethodKeys = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/subscriptions/acknowledged": null +}; +/** The 2026-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +/** The 2026-era notification-method set. */ +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +/** Result-map membership (same key set as the request map on this era). */ +function hasResultMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function getRequestSchema2026(method) { + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; +} +function getResultSchema2026(method) { + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; +} +function getNotificationSchema2026(method) { + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2026RequestMethods = Object.keys(requestMethodKeys); +const rev2026NotificationMethods = Object.keys(notificationMethodKeys); + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/codec.ts +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA = { + ok: false, + reason: "not-in-era" +}; +/** +* The reserved `_meta` keys an envelope must carry on this era (in reporting +* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a +* request without it is accepted (a present-but-malformed value still fails +* the envelope schema parse below). +*/ +const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; +/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ +function enforceDeletedFields(method, result) { + let next = result; + let copied = false; + const copy = () => { + if (!copied) { + next = { ...next }; + copied = true; + } + return next; + }; + const tools = result.tools; + if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { + if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; + const rest = { ...tool }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$4(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy().capabilities = rest; + } + return next; +} +const rev2026Codec = { + era: "2026-07-28", + hasRequestMethod: hasRequestMethod2026, + hasNotificationMethod: hasNotificationMethod2026, + hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, + validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), + validateResult: (method, raw) => triState(getResultSchema2026(method), raw), + validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), + validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), + validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), + samplingResultVariant: () => NOT_IN_ERA, + outboundEnvelope(material) { + return { + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); + if (!parsed.success) for (const issue of parsed.error.issues) { + const path = issue.path.map(String); + const key = path.length > 0 ? path.join(".") : "_meta"; + if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; + issues.push({ + key, + problem: issue.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$4(raw)) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { + method, + violation: "input-required-missing-both" + }) + }; + return { + kind: "input_required", + inputRequests, + ...typeof requestState === "string" && { requestState } + }; + } + if (rawResultType !== "complete") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { + resultType: rawResultType, + method + }) + }; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; + if (wireSchema !== void 0) { + const parsed = wireSchema.safeParse(raw); + if (!parsed.success) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) + }; + } + const lifted = { ...raw }; + delete lifted["resultType"]; + return { + kind: "complete", + result: lifted + }; + }, + encodeResult(method, result, serverInfo) { + return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope(material) { + if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); + if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; + } +}; +/** Wire-true result wrappers consulted by decode step 2, keyed by method — +* built once through the era's schema memo on the first decode. */ +let wireResultSchemasMemo; +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s.CallToolResultSchema, + "tools/list": s.ListToolsResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "completion/complete": s.CompleteResultSchema, + "server/discover": s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +/** +* Forces the lazy wire-result wrapper map (and, through it, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. +*/ +function warmWireResultSchemas2026() { + getWireResultSchemas(); +} + +//#endregion +//#region ../core-internal/src/wire/codec.ts +/** +* The modern wire revision literal. Internal only — deliberately NOT a public +* constant (G-D2-4: no public modern-version constant ships before era-aware +* list semantics exist). +*/ +const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; +/** +* Era resolution, many-to-one (Q1-SD1): every modern-era revision +* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five +* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era +* codec (the DV-13 default posture — hand-constructed instances and +* unclassified traffic are legacy-era). This is the same era predicate the +* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern +* revision other than the literal '2026-07-28' must still resolve modern. +*/ +function src_CX2iR2pK_codecForVersion(version) { + return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; +} +/** +* The wire era an edge classification names (Q2 — produced at the +* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no +* longer resolves a codec FROM the classification: era is instance state, and +* a classified inbound message is VALIDATED against the instance era — a +* mismatch is an entry/routing error, never a per-message era switch. The +* exact `revision` wins over the coarse era flag when both are present. +*/ +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +/** +* The derived spec-method universe: the union of every codec registry. A +* method in this set is era-gated at dispatch and send time; a method outside +* it is a consumer-owned extension method (era-blind, schema-explicit). +* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS +* table class is exactly what registry membership replaces). +*/ +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); +} +const ALL_CODECS = [rev2025Codec, rev2026Codec]; + +//#endregion +//#region ../core-internal/src/shared/envelope.ts +/** +* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). +* +* Pure, value-returning helpers used by the inbound HTTP classifier +* (`classifyInboundRequest`): claim detection and envelope validation with +* self-identifying issues. The envelope schema itself stays the wire layer's +* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps +* its outcomes into the shapes the validation ladder emits. +* +* Claim detection is deliberately narrow: a message claims the 2026-07-28 +* envelope mechanism if and only if the reserved protocol-version `_meta` key +* is present in `params._meta`. Other reserved keys (client info, client +* capabilities, log level), a bare `progressToken`, or unrelated keys under +* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their +* own — but once the claim key is present, a malformed envelope is a +* validation error, never a silent fall back to legacy handling. +* +* The wire-exact envelope schema, the required-key set, and the per-key issue +* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). +* This module never reaches into a per-revision wire module directly. +*/ +function isPlainObject$3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** The `_meta` object of a message's params, when present. */ +function src_CX2iR2pK_requestMetaOf(params) { + if (!isPlainObject$3(params)) return void 0; + const meta = params["_meta"]; + return isPlainObject$3(meta) ? meta : void 0; +} +/** +* Whether a message's params carry the per-request envelope claim: the +* reserved protocol-version `_meta` key is present (regardless of whether the +* rest of the envelope is valid — validation is a separate, later step). +*/ +function src_CX2iR2pK_hasEnvelopeClaim(params) { + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; +} +/** +* The protocol version named by a message's envelope claim, when the claim is +* present and carries a string value. A present claim with a non-string value +* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a +* validation issue instead of a version. +*/ +function src_CX2iR2pK_envelopeClaimVersion(params) { + const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; + return typeof value === "string" ? value : void 0; +} +/** +* Validates a request's `_meta` object as a 2026-07-28 per-request envelope +* and reports problems as self-identifying issues (which key, what problem). +* +* Returns an empty array when the envelope is valid. Missing required keys are +* reported first (as `problem: 'missing'`), then schema violations inside +* present keys, in a stable order. +*/ +function src_CX2iR2pK_validateEnvelopeMeta(meta) { + return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); +} + +//#endregion +//#region ../core-internal/src/types/schemas.ts +var schemas_exports = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, + CancelTaskRequestSchema: () => CancelTaskRequestSchema, + CancelTaskResultSchema: () => CancelTaskResultSchema, + CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, + CancelledNotificationSchema: () => CancelledNotificationSchema, + ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, + ClientNotificationSchema: () => ClientNotificationSchema, + ClientRequestSchema: () => ClientRequestSchema, + ClientResultSchema: () => ClientResultSchema, + ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, + CompleteRequestSchema: () => CompleteRequestSchema, + CompleteResultSchema: () => CompleteResultSchema, + ContentBlockSchema: () => ContentBlockSchema, + CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, + CreateMessageRequestSchema: () => CreateMessageRequestSchema, + CreateMessageResultSchema: () => CreateMessageResultSchema, + CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, + CreateTaskResultSchema: () => CreateTaskResultSchema, + CursorSchema: () => CursorSchema, + DiscoverRequestSchema: () => DiscoverRequestSchema, + DiscoverResultSchema: () => DiscoverResultSchema, + ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, + ElicitRequestSchema: () => ElicitRequestSchema, + ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, + ElicitResultSchema: () => ElicitResultSchema, + ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, + EmbeddedResourceSchema: () => EmbeddedResourceSchema, + EmptyResultSchema: () => EmptyResultSchema, + EnumSchemaSchema: () => EnumSchemaSchema, + GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, + GetPromptRequestSchema: () => GetPromptRequestSchema, + GetPromptResultSchema: () => GetPromptResultSchema, + GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, + GetTaskRequestSchema: () => GetTaskRequestSchema, + GetTaskResultSchema: () => GetTaskResultSchema, + IconSchema: () => IconSchema, + IconsSchema: () => IconsSchema, + ImageContentSchema: () => ImageContentSchema, + ImplementationSchema: () => ImplementationSchema, + InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, + InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, + JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, + JSONValueSchema: () => JSONValueSchema, + LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, + ListPromptsRequestSchema: () => ListPromptsRequestSchema, + ListPromptsResultSchema: () => ListPromptsResultSchema, + ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, + ListResourcesRequestSchema: () => ListResourcesRequestSchema, + ListResourcesResultSchema: () => ListResourcesResultSchema, + ListRootsRequestSchema: () => ListRootsRequestSchema, + ListRootsResultSchema: () => ListRootsResultSchema, + ListTasksRequestSchema: () => ListTasksRequestSchema, + ListTasksResultSchema: () => ListTasksResultSchema, + ListToolsRequestSchema: () => ListToolsRequestSchema, + ListToolsResultSchema: () => ListToolsResultSchema, + LoggingLevelSchema: () => LoggingLevelSchema, + LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, + ModelHintSchema: () => ModelHintSchema, + ModelPreferencesSchema: () => ModelPreferencesSchema, + MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, + NotificationSchema: () => NotificationSchema, + NotificationsParamsSchema: () => NotificationsParamsSchema, + NumberSchemaSchema: () => NumberSchemaSchema, + PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, + PaginatedRequestSchema: () => PaginatedRequestSchema, + PaginatedResultSchema: () => PaginatedResultSchema, + PingRequestSchema: () => PingRequestSchema, + PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, + ProgressNotificationSchema: () => ProgressNotificationSchema, + ProgressSchema: () => ProgressSchema, + ProgressTokenSchema: () => ProgressTokenSchema, + PromptArgumentSchema: () => PromptArgumentSchema, + PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, + PromptMessageSchema: () => PromptMessageSchema, + PromptReferenceSchema: () => PromptReferenceSchema, + PromptSchema: () => PromptSchema, + ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, + ReadResourceRequestSchema: () => ReadResourceRequestSchema, + ReadResourceResultSchema: () => ReadResourceResultSchema, + RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, + RequestIdSchema: () => RequestIdSchema, + RequestMetaSchema: () => RequestMetaSchema, + RequestSchema: () => RequestSchema, + ResourceContentsSchema: () => ResourceContentsSchema, + ResourceLinkSchema: () => ResourceLinkSchema, + ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, + ResourceSchema: () => ResourceSchema, + ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, + ResourceTemplateSchema: () => ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, + ResultMetaObjectSchema: () => ResultMetaObjectSchema, + ResultSchema: () => ResultSchema, + RoleSchema: () => RoleSchema, + RootSchema: () => RootSchema, + RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, + SamplingContentSchema: () => SamplingContentSchema, + SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, + SamplingMessageSchema: () => SamplingMessageSchema, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, + ServerNotificationSchema: () => ServerNotificationSchema, + ServerRequestSchema: () => ServerRequestSchema, + ServerResultSchema: () => ServerResultSchema, + ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, + SetLevelRequestSchema: () => SetLevelRequestSchema, + SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, + StringSchemaSchema: () => StringSchemaSchema, + SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, + SubscribeRequestSchema: () => SubscribeRequestSchema, + SubscriptionFilterSchema: () => SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema: () => TaskCreationParamsSchema, + TaskMetadataSchema: () => TaskMetadataSchema, + TaskSchema: () => TaskSchema, + TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, + TaskStatusSchema: () => TaskStatusSchema, + TextContentSchema: () => TextContentSchema, + TextResourceContentsSchema: () => TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema: () => ToolAnnotationsSchema, + ToolChoiceSchema: () => ToolChoiceSchema, + ToolExecutionSchema: () => ToolExecutionSchema, + ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, + ToolResultContentSchema: () => ToolResultContentSchema, + ToolSchema: () => ToolSchema, + ToolUseContentSchema: () => ToolUseContentSchema, + UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema +}); + +//#endregion +//#region ../core-internal/src/types/guards.ts +/** +* Validates and parses an unknown value as a JSON-RPC message. +* +* Use this to validate incoming messages in custom transport implementations. +* Throws if the value does not conform to the JSON-RPC message schema. +* +* @param value - The value to validate (typically a parsed JSON object). +* @returns The validated {@linkcode JSONRPCMessage}. +* @throws If validation fails. +*/ +function parseJSONRPCMessage(value) { + return JSONRPCMessageSchema.parse(value); +} +const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. +*/ +const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode CallToolResult}. +* +* This is a consumer-side VALUE check against the neutral model, not a wire +* validator: a raw wire object that additionally carries wire-only members +* (e.g. `resultType`) still passes through the loose index signature. Use a +* transport-level parse to validate raw wire traffic. +* +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. +*/ +const isCallToolResult = (value) => { + if (typeof value !== "object" || value === null || value.content === void 0) return false; + return CallToolResultSchema.safeParse(value).success; +}; +/** +* Checks whether a value is an input-required result (protocol revision +* 2026-07-28): the multi-round-trip return shape discriminated by +* `resultType: 'input_required'`. +* +* This is a discriminator check, not a full validator — the at-least-one rule +* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` +* builder and re-checked by the server seam for hand-built values. +* +* @param value - The value to check. +* @returns True if the value carries the `input_required` discriminator. +*/ +const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; +/** +* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. +* +* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK +* runtime; kept importable for interoperability only. +*/ +const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); +} + +//#endregion +//#region ../core-internal/src/shared/mcpParamHeaders.ts +/** The fixed prefix every custom-parameter header carries. */ +const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; +/** The schema-extension property name a tool's `inputSchema` carries. */ +const X_MCP_HEADER_KEY = "x-mcp-header"; +/** +* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control +* characters (including CR/LF), and the listed delimiters. +*/ +const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +/** +* JSON Schema `type` values the spec admits on an `x-mcp-header` property. +* +* The spec text names `integer`, `string`, `boolean` and explicitly excludes +* `number`. The published conformance referee at the pinned release ships its +* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` +* parameters and expects the client to mirror them, so `number` is accepted +* here so that the conformance gate passes; the discrepancy is tracked +* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. +*/ +const PERMITTED_X_MCP_HEADER_TYPES = new Set([ + "string", + "integer", + "boolean", + "number" +]); +/** +* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations +* and validate every constraint the spec places on them. Returns either the +* collected declarations (possibly empty) or the first violated constraint. +* +* The walk descends through `properties` at any depth (the spec's "any nesting +* depth" clause). The static-reachability MUST is enforced as a structural +* sweep: every position the chain MUST NOT pass through (`items`/ +* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, +* `$defs`, `$ref` targets within `$defs`) is visited too, and an +* `x-mcp-header` found anywhere on that path invalidates the schema — "an +* annotation anywhere else makes the tool definition invalid". +*/ +function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { + const declarations = []; + const seenLower = /* @__PURE__ */ new Map(); + const visit = (node, path, reachable) => { + if (node === null || typeof node !== "object") return void 0; + const schema = node; + if (X_MCP_HEADER_KEY in schema) { + if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; + const raw = schema[X_MCP_HEADER_KEY]; + if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; + if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; + const type = typeof schema.type === "string" ? schema.type : void 0; + if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; + const lower = raw.toLowerCase(); + const prior = seenLower.get(lower); + if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; + seenLower.set(lower, raw); + declarations.push({ + path, + headerName: raw, + type + }); + } + const properties = schema.properties; + if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { + const fault$1 = visit(child, [...path, key], reachable); + if (fault$1 !== void 0) return fault$1; + } + for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { + const sub = schema[k]; + if (sub === void 0) continue; + const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; + for (const branch of branches) { + const fault$1 = visit(branch, [...path, `<${k}>`], false); + if (fault$1 !== void 0) return fault$1; + } + } + }; + const fault = visit(inputSchema, [], true); + return fault === void 0 ? { + valid: true, + declarations + } : { + valid: false, + reason: fault + }; +} +/** +* JSON Schema keywords whose subschemas the SEP-2243 static-reachability +* constraint excludes from the `properties`-only chain. An `x-mcp-header` +* found under any of these invalidates the tool definition. +*/ +const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "$defs", + "definitions" +]; +/** +* Subschema-carrying keywords whose value is a `name → subschema` object +* (not a single subschema or array of subschemas). The visit branches over +* `Object.values()` for these. +*/ +const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ + "patternProperties", + "dependentSchemas", + "$defs", + "definitions" +]); +function pathName(path) { + return path.length === 0 ? "" : path.join("."); +} +const BASE64_SENTINEL_PREFIX = "=?base64?"; +const BASE64_SENTINEL_SUFFIX = "?="; +const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; +/** +* Convert a primitive argument value to its string representation per the +* spec's type-conversion rules: strings pass through, integers and numbers +* become their decimal string, booleans become lowercase `'true'` / `'false'`. +* Non-finite numbers and integers outside the safe range are refused (the +* caller treats `undefined` as "do not emit a header for this value"). +*/ +function mcpParamPrimitiveToString(value) { + if (typeof value === "string") return value; + if (typeof value === "boolean") return value ? "true" : "false"; + if (typeof value === "number") { + if (!Number.isFinite(value)) return void 0; + if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; + return String(value); + } +} +function base64ToUtf8(b64) { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); +} +/** +* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, +* the payload is decoded as UTF-8; otherwise the value is returned as-is. +* Returns `undefined` when the sentinel is present but the payload is not +* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject +* such values. +*/ +function decodeMcpParamValue(value) { + if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; + const b64 = value.slice(9, value.length - 2); + if (!BASE64_CANONICAL.test(b64)) return void 0; + try { + return base64ToUtf8(b64); + } catch { + return; + } +} +function valueAtPath(root, path) { + let node = root; + for (const key of path) { + if (node === null || typeof node !== "object") return void 0; + node = node[key]; + } + return node; +} +/** +* The header/body comparison the server performs at tool-resolution time. +* +* For each `x-mcp-header` declaration on the named tool: when the body +* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be +* present and decode to an equal value; when the body value is `null` or +* absent the server MUST NOT expect the header (a present header is ignored). +* A sentinel-carrying header whose payload is not canonical Base64 / valid +* UTF-8 is rejected as invalid characters. +* +* Integer-typed declarations are compared numerically (the spec's SHOULD — +* `42.0` and `42` are equal); everything else is compared as decoded strings. +* +* Returns `undefined` when every check passes, or an +* {@linkcode InboundLadderRejection} carrying the same `-32020` +* (`HeaderMismatch`) shape the inbound classifier emits for the +* standard-header cross-checks — `400 Bad Request` with the disagreeing pair +* in `data.mismatch`. +*/ +function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { + for (const decl of declarations) { + const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; + const headerValue = headers.get(headerKey); + const bodyRaw = valueAtPath(args, decl.path); + if (bodyRaw === void 0 || bodyRaw === null) continue; + const bodyString = mcpParamPrimitiveToString(bodyRaw); + if (bodyString === void 0) continue; + if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); + const decoded = decodeMcpParamValue(headerValue); + if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); + if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); + } +} +/** +* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` +* disagreement. Same shape as the inbound classifier's standard-header +* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing +* pair, `settled: true`); only the rung differs because this check runs at the +* pre-dispatch step against a known tool's schema rather than at the edge. +*/ +function paramHeaderMismatchRejection(cell, header, body) { + return { + kind: "reject", + rung: "param-header-validation", + cell, + httpStatus: 400, + code: HEADER_MISMATCH_ERROR_CODE, + message: `Bad Request: the request headers and body disagree: ${body}`, + data: { mismatch: { + header, + body + } }, + settled: true + }; +} + +//#endregion +//#region ../core-internal/src/shared/inboundClassification.ts +/** +* Inbound HTTP request classification and the inbound validation ladder +* (protocol revision 2026-07-28). +* +* `classifyInboundRequest` is the body-primary era predicate for an HTTP +* entry that serves both protocol eras on one endpoint. It is evaluated +* exactly once, at the entry boundary, on the already-parsed request body: +* +* - `initialize` is a legacy-era request by definition (the modern era has no +* `initialize` handshake) — unless it carries a valid envelope claim naming +* a modern revision, in which case the claim wins and the request is +* classified like any other enveloped request (the modern era then answers +* it with method-not-found, exactly like every other method it does not +* define). +* - A request whose `params._meta` carries the reserved protocol-version key +* claims the per-request envelope mechanism and classifies into the era the +* named revision belongs to (a malformed envelope behind a present claim is +* a validation error, never a silent fall back to legacy handling). +* - A request without a claim is legacy-era traffic. +* - The `MCP-Protocol-Version` header is a cross-check only: it never +* upgrades or downgrades a body-derived classification, and a disagreement +* between header and body is an explicit ladder outcome. +* - Notifications carry no envelope claim of their own under the current +* spec, so for notification POSTs without a body claim the modern header is +* determinative; the `Mcp-Method` header is validated against the body when +* the message classifies modern and is never enforced on legacy traffic. +* A notification that does carry a claim is treated body-primary like a +* request, and a malformed claim is rejected the same way a request's +* malformed claim is — never silently resolved against the header. +* The notification-POST header cross-checks here are an SDK-defensive +* posture, not a spec requirement: the spec leaves header rules for posted +* notifications undefined (core client notifications do not occur over +* Streamable HTTP); applying the request rules symmetrically is what an +* ecosystem custom-notification POST expects, and the −32020 cells stay +* passing for them. +* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era +* session operations: the modern era is `POST`-only, so they are routed to +* legacy serving when it is configured and rejected otherwise. +* - Array (batch) bodies are classified element-wise: an array containing a +* modern-claiming or invalid element is rejected, an all-legacy array is +* legacy traffic unchanged, and a single-element array is still an array. +* +* The classifier returns plain values (it never throws and never touches a +* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection +* carrying the JSON-RPC error to emit and the HTTP status to emit it with. +* Legacy routing outcomes deliberately carry NO `MessageClassification` — +* legacy and hand-wired traffic is never classified, which keeps its +* dispatch behavior byte-identical to today's. +* +* Error codes for the modern-path rejection cells follow the published +* conformance suite (and the spec text it asserts): +* +* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header +* disagreeing with the body, or the `Mcp-Method` header disagreeing with the +* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. +* - A request whose protocol-version header names a modern revision but whose +* body carries no `_meta` envelope claim — including an envelope present but +* missing the required protocol-version key — is rejected with `-32602` +* (invalid params) naming the missing key(s), on HTTP 400. +* +* Should a future spec revision or conformance release change these +* assignments, the affected cells are re-derived against that release; the +* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark +* a cell provisional again while such a change is in flight. +*/ +/** +* The error code emitted for header/body cross-check mismatches: the +* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or +* with the body's classification), and the `Mcp-Method` header disagreeing +* with the body method. +* +* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 +* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted +* by the published conformance suite for header-validation failures. It has no +* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era +* wire vocabulary; the validation ladder is its only emitter. +*/ +const HEADER_MISMATCH_ERROR_CODE = -32020; +/** +* The inbound validation ladder, expressed as data rather than control flow. +* +* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the +* dispatch rungs are evaluated by the protocol layer once the classified +* message is injected into a per-request server instance (the era registry +* gate, the envelope requiredness check, and per-method params validation). +* The client-capability rung is evaluated by the HTTP entry itself, +* pre-dispatch, on the validated envelope the classifier produced — see that +* rung's rationale for the ordering caveat. The order is the precedence: a +* request that fails several rungs is answered by the earliest one. +*/ +const INBOUND_VALIDATION_LADDER = [ + { + rung: "http-method", + order: 1, + evaluatedAt: "edge", + codes: [-32e3], + conformance: [], + rationale: "The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read." + }, + { + rung: "jsonrpc-shape", + order: 2, + evaluatedAt: "edge", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest], + conformance: ["server-stateless"], + rationale: "The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic." + }, + { + rung: "era-classification", + order: 3, + evaluatedAt: "edge", + codes: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion], + conformance: [ + "server-stateless", + "http-header-validation", + "http-custom-header-server-validation" + ], + rationale: "Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions." + }, + { + rung: "envelope", + order: 4, + evaluatedAt: "edge", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." + }, + { + rung: "method-registry", + order: 5, + evaluatedAt: "dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." + }, + { + rung: "request-params", + order: 6, + evaluatedAt: "dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: [], + rationale: "Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table." + }, + { + rung: "standard-header-validation", + order: 7, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-header-validation"], + rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." + }, + { + rung: "param-header-validation", + order: 9, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." + } +]; +/** +* HTTP status for ladder-originated JSON-RPC error codes. +* +* Keyed on origin, not on the bare code: this table only applies to errors +* the ladder (or a pre-handler protocol gate) produced. Errors produced by +* request handlers — whatever their code — stay in-band on HTTP 200, and are +* never mapped to an HTTP status by this table; in particular `-32603` and +* domain-specific codes never become a blanket 500. The single exception is +* `MissingRequiredClientCapability` (-32021) — see +* {@linkcode httpStatusForErrorCode}. +* +* `-32602` (invalid params) deliberately has NO entry: the only invalid-params +* rejection that maps to HTTP 400 is the classifier's own envelope rung +* short-circuit, which carries its HTTP status directly. A dispatch- or +* handler-produced invalid-params error is always in-band. +*/ +const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { + [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, + [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, + [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 +}; +/** +* The HTTP status to answer a JSON-RPC error with, keyed on the error's +* origin. `in-band` errors (anything produced by a request handler) are +* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP +* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), +* whose 400 the spec mandates on the error itself with no origin condition, +* and which the SDK genuinely produces after dispatch (the `input_required` +* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` +* is NOT that peer's spec error and stays in-band like every other handler +* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. +* +* The per-request transport intentionally does NOT delegate to this function: +* its `?? 400` ladder fallback is only correct for entry-gate codes known to +* the table, and would wrongly map dispatch-window errors outside it (a +* window `-32602` must stay in-band on 200). The transport indexes the table +* directly; keep the two in agreement when editing either. +*/ +function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { + if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; + return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; +} +function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { + return { + kind: "reject", + rung, + cell, + httpStatus, + code: error.code, + message: error.message, + ...error.data !== void 0 && { data: error.data }, + settled + }; +} +function crossCheckMismatch(cell, header, body, rung = "era-classification") { + return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { + header, + body + } }), true); +} +/** +* The methods whose body carries a `params.name` / `params.uri` value the +* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 +* § Standard Request Headers, `Required For` column). +*/ +const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ + "tools/call": "name", + "prompts/get": "name", + "resources/read": "uri" +})); +/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ +function stripHttpOws(value) { + let start = 0; + while (start < value.length) { + const code = value.codePointAt(start); + if (code !== 9 && code !== 32) break; + start += 1; + } + let end = value.length; + while (end > start) { + const code = value.codePointAt(end - 1); + if (code !== 9 && code !== 32) break; + end -= 1; + } + return start === 0 && end === value.length ? value : value.slice(start, end); +} +/** +* SEP-2243 standard-header server-side validation, evaluated by the HTTP +* entry on a modern-classified request immediately after +* {@linkcode classifyInboundRequest} returns a modern route. +* +* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, +* `standard-header-validation` rung — the same shape +* {@linkcode classifyInboundRequest} already emits on the edge +* `era-classification` rung for the `MCP-Protocol-Version` and +* `Mcp-Method` *mismatch* cells) when: +* +* - the required `Mcp-Method` header is absent; +* - the required `Mcp-Name` header is absent on a `tools/call`, +* `prompts/get`, or `resources/read` request whose body carries the +* `params.name` / `params.uri` value the header mirrors; +* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or +* - the (decoded) `Mcp-Name` value disagrees with the body's +* `params.name` / `params.uri`. +* +* Returns `undefined` (pass) for notifications (the spec table reads +* "All requests"), for methods that have no `Mcp-Name` source, and when the +* headers agree with the body. Never enforced on legacy traffic — the entry +* only calls this on a modern route. +* +* Kept separate from {@linkcode classifyInboundRequest} so that a body-only +* call to the classifier (no headers passed) keeps routing a modern request +* unchanged: the classifier remains a pure body-primary router, and this +* function is the presence/`Mcp-Name` half of the standard-header rung the +* entry layers on top. +*/ +function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { + if (route.messageKind !== "request") return; + const method = route.message.method; + if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); + const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; + if (sourceField === void 0) return; + const sourceValue = route.message.params?.[sourceField]; + const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; + if (request.mcpNameHeader === void 0) { + if (bodyValue === void 0) return; + return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); + } + const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); + const decoded = decodeMcpParamValue(normalizedNameHeader); + if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); + if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function classificationForClaim(claimedVersion) { + if (claimedVersion === void 0) return { era: "modern" }; + return { + era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", + revision: claimedVersion + }; +} +/** +* Whether a request's params carry a per-request envelope claim that is both +* well-formed and names a modern protocol revision. +* +* Used by the `initialize` precedence rule: only such a claim overrides the +* `initialize` ⇒ legacy-handshake classification — a request carrying a valid +* modern envelope is a modern request regardless of its method name, and the +* modern era then answers `initialize` exactly like any other method it does +* not define (method-not-found). A malformed claim, or one naming a pre-2026 +* revision, keeps the legacy-handshake routing unchanged. +* +* Exported on the core internal barrel for the stdio serving entry, which +* applies the same precedence rule to a connection's opening message; not +* public API. +*/ +function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { + if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; +} +function classifyBatch(body) { + if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); + for (const element of body) { + if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); + if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); + } + return { + kind: "legacy", + reason: "batch" + }; +} +function classifyRequestBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { + if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); + const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "request", + message: body, + classification: classificationForClaim(claimedVersion) + }; + } + if (headerNamesModern) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); + const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; + return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); + } + return { + kind: "legacy", + reason: "no-claim", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +function classifyNotificationBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { + key: PROTOCOL_VERSION_META_KEY, + problem: "expected a protocol version string" + }; + return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); + } + if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + const classification = classificationForClaim(claimedVersion); + if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification + }; + } + if (headerNamesModern) { + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification: { + era: "modern", + revision: headerVersion + } + }; + } + return { + kind: "legacy", + reason: "notification", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +/** +* Classifies one inbound HTTP request for dual-era serving. +* +* The body-primary predicate, evaluated once at the entry boundary: see the +* module documentation for the rules. Returns a routing outcome (`legacy` or +* `modern`) or a ladder rejection; it never throws. +*/ +function src_CX2iR2pK_classifyInboundRequest(request) { + request = { + ...request, + ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, + ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, + ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } + }; + if (request.httpMethod.toUpperCase() !== "POST") return { + kind: "legacy", + reason: "http-method" + }; + const body = request.body; + if (Array.isArray(body)) return classifyBatch(body); + if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { + kind: "legacy", + reason: "response" + }; + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); + return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); +} +/** +* The rejection a modern-only endpoint (no legacy serving configured) +* answers a legacy-classified request with. +* +* - Envelope-less requests (including `initialize`) are answered with the +* unsupported-protocol-version error carrying the endpoint's supported +* versions and echoing the version the request named (when it named one — +* `requested` is omitted rather than fabricated when the request named no +* version at all), so a legacy client can discover what the endpoint serves +* from the error alone. +* - Posted responses and batch arrays are invalid requests on the modern era. +* - Non-`POST` methods are not allowed. +* - Legacy-classified notifications return `undefined`: the caller answers +* 202 with no body and does not dispatch the notification (accept-and-drop). +*/ +function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { + switch (route.reason) { + case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); + case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); + case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); + case "notification": return; + case "initialize": + case "no-claim": { + const requested = route.requestedVersion; + return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: [...supportedVersions], + requested + }), true); + } + } +} + +//#endregion +//#region ../core-internal/src/util/schema.ts +/** +* Internal Zod schema utilities for protocol handling. +* These are used internally by the SDK for protocol message validation. +*/ +/** +* Parses data against a Zod schema (synchronous). +* Returns a discriminated union with success/error. +*/ +function parseSchema(schema, data) { + return parse_safeParse(schema, data); +} +/** +* Union of the declared shape keys across several Zod object schemas. +*/ +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} + +//#endregion +//#region ../core-internal/src/util/standardSchema.ts +/** +* Standard Schema utilities for user-provided schemas. +* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. +* @see https://standardschema.dev +*/ +function isStandardSchema(schema) { + if (schema == null) return false; + const schemaType = typeof schema; + if (schemaType !== "object" && schemaType !== "function") return false; + if (!("~standard" in schema)) return false; + return typeof schema["~standard"]?.validate === "function"; +} +let warnedZodFallback = false; +/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ +const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; +/** +* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. +* +* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt +* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). +* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, +* so for `io: 'input'` this function defaults `type` to `"object"` when absent +* and throws on an explicit non-object `type` (e.g. `z.string()`). For +* `io: 'output'` a non-object root is returned as-is; the `"object"` default is +* applied only when the root is provably object-shaped. +*/ +function standardSchemaToJsonSchema(schema, io = "input") { + const std = schema["~standard"]; + let result; + if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); + else if (std.vendor === "zod") { + if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema()."); + if (!warnedZodFallback) { + warnedZodFallback = true; + console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning."); + } + result = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io + }); + } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); + if (io === "output") { + if (result.type !== void 0) return result; + return isProvablyObjectShapedRoot(result) ? { + type: "object", + ...result + } : result; + } + if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); + return { + type: "object", + ...result + }; +} +/** +* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords +* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a +* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively +* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to +* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. +*/ +function isProvablyObjectShapedRoot(schema) { + if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; + for (const key of [ + "oneOf", + "anyOf", + "allOf" + ]) { + const members = schema[key]; + if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); + } + return false; +} +function formatIssue(issue) { + if (!issue.path?.length) return issue.message; + return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; +} +async function validateStandardSchema(schema, data) { + const result = await schema["~standard"].validate(data); + if (result.issues && result.issues.length > 0) return { + success: false, + error: result.issues.map((i) => formatIssue(i)).join(", ") + }; + return { + success: true, + data: result.value + }; +} +function zodEmittedPattern(schema) { + const jsonSchema = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io: "input" + }); + return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; +} +const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; +function datetimeReferenceSchemas(pattern) { + const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); + const precisions = [ + void 0, + -1, + 0 + ]; + if (fractionDigits) precisions.push(Number(fractionDigits[1])); + return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [schemas_email()]; + break; + case "uri": + referenceSchemas = [schemas_url()]; + break; + case "date": + referenceSchemas = [iso_date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function promptArgumentsFromStandardSchema(schema) { + const jsonSchema = standardSchemaToJsonSchema(schema, "input"); + const properties = jsonSchema.properties || {}; + const required = jsonSchema.required || []; + return Object.entries(properties).map(([name, prop]) => ({ + name, + description: prop?.description, + required: required.includes(name) + })); +} + +//#endregion +//#region ../core-internal/src/shared/elicitation.ts +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); +const PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) +}; +const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); +/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ +function walkProperty(node, path, vendor, unsupported) { + if (!isJsonObject(node)) return node; + const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; + if (allowedKeys === void 0) return node; + const pruned = {}; + for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; + else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { + if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; + else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); + } else unsupported.push(`${path}.${key}`); + return pruned; +} +/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ +function walkRequestedSchema(converted, vendor) { + const pruned = {}; + const unsupported = []; + for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); + else if (ROOT_KEYS.has(key)) pruned[key] = value; + else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); + if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ +function describeUnsupportedProperties(pruned, fallback) { + if (!isJsonObject(pruned.properties)) return fallback; + const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); + return offenders.length > 0 ? offenders.join(", ") : fallback; +} +function findDroppedConstraintPaths(original, parsed, path = "") { + if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); + if (!isJsonObject(original) || !isJsonObject(parsed)) return []; + return Object.entries(original).flatMap(([key, value]) => { + const childPath = path ? `${path}.${key}` : key; + if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; + return findDroppedConstraintPaths(value, parsed[key], childPath); + }); +} +/** Converts an authoring-friendly elicitation input into its wire-ready form. */ +function normalizeElicitInputParams(input) { + if (!isStandardSchema(input.requestedSchema)) return { + ...input, + mode: "form", + requestedSchema: input.requestedSchema + }; + const vendor = input.requestedSchema["~standard"].vendor; + const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); + const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); + const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); + if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); + const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); + if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequired.ts +/** +* Authoring helpers for multi-round-trip requests (protocol revision +* 2026-07-28). +* +* A handler for one of the multi-round-trip methods (`tools/call`, +* `prompts/get`, `resources/read`) requests additional client input by +* returning an {@linkcode InputRequiredResult} instead of a final result. The +* helpers here build that return value and its embedded requests as NEUTRAL +* values; only the 2026-07-28 wire codec maps them to/from the wire. The +* 2025-era codec has no input-required vocabulary — on a 2025-era request the +* server's legacy shim (on by default) fulfils the embedded requests as real +* server→client requests and re-enters the handler, so the same return shape +* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores +* the pre-shim loud failure. +* +* There is no nominal brand: `resultType: 'input_required'` is the +* discriminator, and hand-built result literals are equally legal — the +* server seam re-checks the at-least-one rule for them. +*/ +function buildInputRequired(spec) { + const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; + const hasRequestState = typeof spec.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)"); + return { + resultType: "input_required", + ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, + ...spec.requestState !== void 0 && { requestState: spec.requestState } + }; +} +/** +* Builder for the input-required return value of multi-round-trip handlers, +* with per-kind constructors for the embedded requests +* (`inputRequired.elicit`, `inputRequired.elicitUrl`, +* `inputRequired.createMessage`, `inputRequired.listRoots`). +* +* @example Write-once tool requesting confirmation +* ```ts +* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { +* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); +* if (!confirmed) { +* return inputRequired({ +* inputRequests: { +* confirm: inputRequired.elicit({ +* message: `Deploy to ${env}?`, +* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } +* }) +* } +* }); +* } +* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; +* }); +* ``` +*/ +const inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error) { + throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } +}); +function acceptedContent(responses, key, schema) { + const view = inputResponse(responses, key); + if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; + if (schema === void 0) return view.content; + const outcome = schema["~standard"].validate(view.content); + if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); + return outcome.issues === void 0 ? outcome.value : void 0; +} +/** +* Reads one entry of a retried request's `inputResponses` +* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering +* decline/cancel detection and the non-elicitation response kinds that +* {@linkcode acceptedContent} does not surface. +* +* The values arrive from the client and are not re-validated here — treat +* them as untrusted input (validate elicitation content with the +* schema-aware {@linkcode acceptedContent} overload where it matters). +*/ +function inputResponse(responses, key) { + if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; + const entry = responses[key]; + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; + const candidate = entry; + if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { + const content = candidate["content"]; + return { + kind: "elicit", + action: candidate["action"], + ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } + }; + } + if (Array.isArray(candidate["roots"])) return { + kind: "roots", + roots: candidate["roots"] + }; + if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { + kind: "sampling", + result: candidate + }; + return { kind: "missing" }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredDriver.ts +/** +* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). +* +* When a request to one of the multi-round-trip methods comes back as +* `input_required`, the driver fulfils the embedded input requests by +* dispatching them to the client's already-registered handlers (elicitation, +* sampling, roots — one generic engine, no per-feature API), then retries the +* original request with the collected `inputResponses` and a byte-exact echo +* of `requestState`, on a fresh request id, until the server returns a +* complete result or the round cap is exhausted. +* +* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the +* same primitive a manual caller uses (`allowInputRequired` semantics — the +* retry hands back the next `input_required` payload instead of recursing), +* so the loop, the cap, and the pacing live in one place and disabling +* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this +* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to +* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by +* shrinking the budget passed to each leg — no new timer system. +*/ +/** +* Fixed pacing applied before retrying a requestState-only (load-shedding) +* leg — a leg that carries no embedded input requests, so nothing slows the +* loop down naturally. Counted in the same round cap. +*/ +const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; +/** +* The message both multi-round-trip loops emit when the round cap is +* exhausted — the client driver as a typed error, the server-side legacy +* shim as its per-family failure. One formatter so the texts cannot drift +* (hosts and models read the tool-result copy verbatim). +*/ +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +/** +* Abortable delay: resolves after `ms`, or rejects with the signal's reason +* (wrapped in an `SdkError` when it isn't already one) if the signal aborts +* first. Aborting after resolution is a no-op. Shared with the server-side +* legacy shim (the pacing semantics must match per era). +*/ +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +/** +* A per-round abort linked to the caller's signal: the embedded sibling +* dispatches share it, so the first failure (or a caller abort) cancels the +* others instead of leaving them running. Shared with the server-side legacy +* shim (the abort-linkage semantics must match per era). +*/ +function linkedRoundAbort(outer) { + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(outer?.reason); + outer?.addEventListener("abort", onOuterAbort, { once: true }); + if (outer?.aborted) controller.abort(outer.reason); + return { + signal: controller.signal, + abort: (reason) => controller.abort(reason), + dispose: () => outer?.removeEventListener("abort", onOuterAbort) + }; +} + +//#endregion +//#region ../core-internal/src/types/specTypeSchema.ts +/** +* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. +* +* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no +* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, +* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). +* Keeping the list explicit means new public spec types must be added here deliberately, and +* internals never leak into `SpecTypeName`. +* +* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` +* (the bare name collides with the server package's `ResourceTemplate` class), so +* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to +* a type literally named `ResourceTemplate`. +*/ +const SPEC_SCHEMA_KEYS = [ + "AnnotationsSchema", + "AudioContentSchema", + "BaseMetadataSchema", + "BlobResourceContentsSchema", + "BooleanSchemaSchema", + "CallToolRequestSchema", + "CallToolRequestParamsSchema", + "CallToolResultSchema", + "CancelledNotificationSchema", + "CancelledNotificationParamsSchema", + "CancelTaskRequestSchema", + "CancelTaskResultSchema", + "ClientCapabilitiesSchema", + "ClientNotificationSchema", + "ClientRequestSchema", + "ClientResultSchema", + "CompatibilityCallToolResultSchema", + "CompleteRequestSchema", + "CompleteRequestParamsSchema", + "CompleteResultSchema", + "ContentBlockSchema", + "CreateMessageRequestSchema", + "CreateMessageRequestParamsSchema", + "CreateMessageResultSchema", + "CreateMessageResultWithToolsSchema", + "CreateTaskResultSchema", + "CursorSchema", + "DiscoverRequestSchema", + "DiscoverResultSchema", + "ElicitationCompleteNotificationSchema", + "ElicitationCompleteNotificationParamsSchema", + "ElicitRequestSchema", + "ElicitRequestFormParamsSchema", + "ElicitRequestParamsSchema", + "ElicitRequestURLParamsSchema", + "ElicitResultSchema", + "EmbeddedResourceSchema", + "EmptyResultSchema", + "EnumSchemaSchema", + "GetPromptRequestSchema", + "GetPromptRequestParamsSchema", + "GetPromptResultSchema", + "GetTaskPayloadRequestSchema", + "GetTaskPayloadResultSchema", + "GetTaskRequestSchema", + "GetTaskResultSchema", + "IconSchema", + "IconsSchema", + "ImageContentSchema", + "ImplementationSchema", + "InitializedNotificationSchema", + "InitializeRequestSchema", + "InitializeRequestParamsSchema", + "InitializeResultSchema", + "JSONArraySchema", + "JSONObjectSchema", + "JSONRPCErrorResponseSchema", + "JSONRPCMessageSchema", + "JSONRPCNotificationSchema", + "JSONRPCRequestSchema", + "JSONRPCResponseSchema", + "JSONRPCResultResponseSchema", + "JSONValueSchema", + "LegacyTitledEnumSchemaSchema", + "ListPromptsRequestSchema", + "ListPromptsResultSchema", + "ListResourcesRequestSchema", + "ListResourcesResultSchema", + "ListResourceTemplatesRequestSchema", + "ListResourceTemplatesResultSchema", + "ListRootsRequestSchema", + "ListRootsResultSchema", + "ListTasksRequestSchema", + "ListTasksResultSchema", + "ListToolsRequestSchema", + "ListToolsResultSchema", + "LoggingLevelSchema", + "LoggingMessageNotificationSchema", + "LoggingMessageNotificationParamsSchema", + "ModelHintSchema", + "ModelPreferencesSchema", + "MultiSelectEnumSchemaSchema", + "NotificationSchema", + "NumberSchemaSchema", + "PaginatedRequestSchema", + "PaginatedRequestParamsSchema", + "PaginatedResultSchema", + "PingRequestSchema", + "PrimitiveSchemaDefinitionSchema", + "ProgressSchema", + "ProgressNotificationSchema", + "ProgressNotificationParamsSchema", + "ProgressTokenSchema", + "PromptSchema", + "PromptArgumentSchema", + "PromptListChangedNotificationSchema", + "PromptMessageSchema", + "PromptReferenceSchema", + "ReadResourceRequestSchema", + "ReadResourceRequestParamsSchema", + "ReadResourceResultSchema", + "RelatedTaskMetadataSchema", + "RequestSchema", + "RequestIdSchema", + "RequestMetaSchema", + "ResourceSchema", + "ResourceContentsSchema", + "ResourceLinkSchema", + "ResourceListChangedNotificationSchema", + "ResourceRequestParamsSchema", + "ResourceTemplateSchema", + "ResourceTemplateReferenceSchema", + "ResourceUpdatedNotificationSchema", + "ResourceUpdatedNotificationParamsSchema", + "ResultMetaObjectSchema", + "ResultSchema", + "RoleSchema", + "RootSchema", + "RootsListChangedNotificationSchema", + "SamplingContentSchema", + "SamplingMessageSchema", + "SamplingMessageContentBlockSchema", + "ServerCapabilitiesSchema", + "ServerNotificationSchema", + "ServerRequestSchema", + "ServerResultSchema", + "SetLevelRequestSchema", + "SetLevelRequestParamsSchema", + "SingleSelectEnumSchemaSchema", + "StringSchemaSchema", + "SubscribeRequestSchema", + "SubscribeRequestParamsSchema", + "SubscriptionFilterSchema", + "SubscriptionsAcknowledgedNotificationSchema", + "SubscriptionsAcknowledgedNotificationParamsSchema", + "SubscriptionsListenRequestSchema", + "SubscriptionsListenRequestParamsSchema", + "SubscriptionsListenResultSchema", + "SubscriptionsListenResultMetaSchema", + "TaskAugmentedRequestParamsSchema", + "TaskCreationParamsSchema", + "TaskMetadataSchema", + "TaskSchema", + "TaskStatusSchema", + "TaskStatusNotificationSchema", + "TaskStatusNotificationParamsSchema", + "TextContentSchema", + "TextResourceContentsSchema", + "TitledMultiSelectEnumSchemaSchema", + "TitledSingleSelectEnumSchemaSchema", + "ToolSchema", + "ToolAnnotationsSchema", + "ToolChoiceSchema", + "ToolExecutionSchema", + "ToolListChangedNotificationSchema", + "ToolResultContentSchema", + "ToolUseContentSchema", + "UnsubscribeRequestSchema", + "UnsubscribeRequestParamsSchema", + "UntitledMultiSelectEnumSchemaSchema", + "UntitledSingleSelectEnumSchemaSchema" +]; +const authSchemas = { + IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, + OAuthClientInformationSchema: OAuthClientInformationSchema, + OAuthClientMetadataSchema: OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema: OAuthErrorResponseSchema, + OAuthMetadataSchema: OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, + OAuthTokensSchema: OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema +}; +const _specTypeSchemas = {}; +const _isSpecType = {}; +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); +for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); +/** +* Runtime validators for every MCP spec type, keyed by type name. +* +* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for +* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from +* storage that should be a `Tool`. +* +* Each entry implements the Standard Schema interface, so it composes with any +* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" +* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); +* if (result.issues === undefined) { +* // result.value is CallToolResult +* } +* ``` +*/ +const specTypeSchemas = Object.freeze(_specTypeSchemas); +/** +* Type predicates for every MCP spec type, keyed by type name. +* +* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and +* transforms are applied), and narrows to that input type. For schemas with `.default()` or +* `.preprocess()`, this may accept values that do not structurally match the named output type; +* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use +* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. +* +* Each guard is a standalone function, so it can be passed directly as a callback. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" +* if (isSpecType.ContentBlock(value)) { +* // value is ContentBlock +* } +* +* const blocks = mixed.filter(isSpecType.ContentBlock); +* ``` +*/ +const isSpecType = Object.freeze(_isSpecType); + +//#endregion +//#region ../core-internal/src/wire/bootstrap.ts +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); + case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); + default: return; + } +} + +//#endregion +//#region ../core-internal/src/shared/protocol.ts +/** +* The default request timeout, in milliseconds. +*/ +const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +/** +* The reserved per-request `_meta` envelope keys (protocol revision +* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before +* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are +* wire-level bookkeeping, not handler material. +*/ +const RESERVED_ENVELOPE_META_KEYS = [ + auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, + auth_CUe6YdwF_CLIENT_INFO_META_KEY, + auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY +]; +/** +* Top-level params members carrying multi-round-trip driver material +* (protocol revision 2026-07-28). The spec reserves these names on +* client-initiated REQUESTS only — notification params keep them untouched +* (a vendor notification may legitimately use the same names). +*/ +const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; +/** +* Lift wire-only material out of an inbound message so handlers see exactly +* the 2025-era shape, and surface it for the protocol layer (requests: via +* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the +* reserved envelope `_meta` keys are reserved on every message, while the +* multi-round-trip retry fields (`inputResponses`/`requestState`) are +* reserved on client-initiated requests only — so notifications get only the +* envelope lift, and their top-level params stay untouched. Messages without +* wire-only material are returned unchanged (same reference). +*/ +function liftWireOnlyMaterial(message, kind) { + const params = message.params; + if (!isPlainObject$1(params)) return { + message, + lifted: {} + }; + const meta = params._meta; + const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { + const envelope = {}; + const nextMeta = { ...meta }; + for (const key of envelopeKeys) { + envelope[key] = meta[key]; + delete nextMeta[key]; + } + lifted.envelope = envelope; + if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; + else delete nextParams._meta; + } + for (const key of retryKeys) { + if (key === "inputResponses") lifted.inputResponses = nextParams[key]; + if (key === "requestState") lifted.requestState = nextParams[key]; + delete nextParams[key]; + } + return { + message: { + ...message, + params: nextParams + }, + lifted + }; +} +/** +* Standard Schema adapter over the era codec's `validateResult` function (the +* function-only WireCodec contract exposes no schema objects). Used by the +* spec-method `request()` overload so the request funnel keeps a single +* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema +* paths. +* +* Returns `undefined` when the method has no result entry on this era's +* registry — the caller maps that to the synchronous "pass a result schema" +* TypeError, exactly matching the pre-function-only behavior the +* typedMapAlignment suite pins (the result map deliberately excludes the +* `tasks/*` methods, so the spec-method overload refuses them up front). +*/ +function codecResultValidator(codec, method) { + const probe = codec.validateResult(method, void 0); + if (!probe.ok && probe.reason === "not-in-era") return void 0; + return { "~standard": { + version: 1, + vendor: "mcp-wire-codec", + validate(value) { + const outcome = codec.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +/** +* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The +* `as T` below is the one place {@linkcode RequestStateAccessor}'s +* caller-asserted typing is implemented — no implementation can produce an +* arbitrary `T` from a runtime value honestly. +*/ +function requestStateAccessor(value) { + return () => value; +} +/** Shared no-state accessor: the common case allocates nothing per request. */ +const NO_REQUEST_STATE = requestStateAccessor(void 0); +/** +* Returns a context whose `requestState` accessor reads the given value — +* how the server seam hands a verify hook's decoded payload (or the legacy +* shim's per-round echo) to the handler without mutating the original +* context. +*/ +function withRequestStateValue(ctx, value) { + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + requestState: requestStateAccessor(value) + } + }; +} +let writeNegotiatedProtocolVersion; +/** +* Package-internal write channel for a {@linkcode Protocol} instance's +* negotiated protocol version, for callers outside the class hierarchy: +* tests and the (future) modern-era server entry that marks a factory +* instance modern at binding time. Exported on the core internal barrel +* only — never public API. +*/ +function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { + writeNegotiatedProtocolVersion(instance, version); +} +/** +* Implements MCP protocol framing on top of a pluggable transport, including +* features like request/response linking, notifications, and progress. +* +* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific +* implementations most code should use. +*/ +var Protocol = class { + _transport; + _requestMessageId = 0; + _requestHandlers = /* @__PURE__ */ new Map(); + _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + _notificationHandlers = /* @__PURE__ */ new Map(); + _responseHandlers = /* @__PURE__ */ new Map(); + _progressHandlers = /* @__PURE__ */ new Map(); + _timeoutInfo = /* @__PURE__ */ new Map(); + _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + /** + * The protocol version negotiated for the current connection (`undefined` + * before negotiation completes), which determines the wire era this + * instance speaks. Set by the SDK's negotiation and initialize paths + * (`Client.connect`, `Server._oninitialize`). + */ + _negotiatedProtocolVersion; + static { + writeNegotiatedProtocolVersion = (instance, version) => { + instance._negotiatedProtocolVersion = version; + }; + } + _supportedProtocolVersions; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when {@linkcode Protocol.close | close()} is called as well. + */ + onclose; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler; + constructor(_options) { + this._options = _options; + this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; + this.setNotificationHandler("notifications/cancelled", (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler("notifications/progress", (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler("ping", (_request) => ({})); + } + /** + * Drop consult for inbound messages whose transport did not classify them + * at the edge — long-lived channels such as stdio, where a role class may + * need to decline traffic the negotiated era has no answer for (the + * client-side inbound-request drop on modern-era connections: the + * 2026-07-28 era has no server→client request channel, and on stdio the + * client must never write JSON-RPC responses). + * + * Consulted ONLY when the transport supplied no + * {@linkcode MessageExtraInfo.classification}: edge-classified traffic + * never reaches the hook. Returning `'drop'` discards the message without + * writing any response (requests are surfaced via `onerror`). The base + * implementation returns `undefined`: unclassified traffic keeps today's + * dispatch path unchanged. Era selection never happens here — era is + * instance state, owned by the serving entry that constructed and + * connected the instance. + */ + _shouldDropInbound(_message) {} + /** + * The per-request `_meta` envelope this instance attaches to every outgoing + * request and notification, when one applies. The base implementation + * returns `undefined` (no envelope — the 2025-era posture, so legacy-era + * outbound traffic is byte-identical to a build without this seam). + * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) + * era to return the reserved protocol-version / client-info / + * client-capabilities keys. User-supplied `_meta` keys take precedence over + * the auto-attached ones. + */ + _outboundMetaEnvelope() {} + /** + * Attach this instance's outbound `_meta` envelope (when one is configured) + * to a request or notification. A no-op when the seam returns `undefined` + * — the message returns by reference, so the legacy-era wire stays + * byte-identical. User-supplied `_meta` keys are spread last so they win + * over the auto-attached envelope keys. + */ + _envelopeOutbound(message) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message; + const params = message.params ?? {}; + return { + ...message, + params: { + ...params, + _meta: { + ...envelope, + ...params._meta + } + } + }; + } + /** + * Extension point for non-`complete` decoded results in the response + * funnel: a result the wire codec discriminated into a kind other than + * `'complete'` or `'invalid'` is handed here for the role class to + * resolve. The base default surfaces it as a typed + * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). + * + * Intended consumers (named so the seam stays accountable): + * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils + * `'input_required'` results through the registered + * elicitation/sampling/roots handlers and retries via `flow.retry`; + * - a future client-side terminal-result handler for + * `subscriptions/listen`, when the spec defines one. + * + * `Server` instances never receive `input_required` responses on their + * outbound legs and leave the base behavior in place. + */ + _resolveNonCompleteResult(decoded, flow) { + return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { + resultType: decoded.kind, + method: flow.request.method + })); + } + /** + * Protected accessor for a registered request handler. Used by role + * classes that dispatch synthesized requests through the same stored + * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip + * input request). + */ + _getRequestHandler(method) { + return this._requestHandlers.get(method); + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + try { + _onclose?.(); + } finally { + this._onclose(); + } + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); + await this._transport.start(); + } + /** + * Transport-close hook. Subclass overrides MUST call `super._onclose()` + * after their own cleanup — base teardown (response-handler settlement, + * timeout clearing, in-flight request abort) does not run otherwise. + */ + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + const requestHandlerAbortControllers = this._requestHandlerAbortControllers; + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + /** + * Inbound-notification dispatch. Subclass overrides MUST delegate + * unmatched traffic to `super._onnotification(rawNotification, extra)` — + * an override that consumes only what it owns and falls through to base + * dispatch for everything else. + */ + _onnotification(rawNotification, extra) { + const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; + const handler = this._notificationHandlers.get(notification.method); + const fallback = this.fallbackNotificationHandler; + if (handler === void 0 && fallback === void 0) return; + Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { + this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); + return; + } + const capturedTransport = this._transport; + const sendErrorResponse = (code, message, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); + return; + } + const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { + ...options, + relatedRequestId: request.id + }); + const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { + ...options, + relatedRequestId: request.id + }); + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); + const baseCtx = { + sessionId: capturedTransport?.sessionId, + mcpReq: { + id: request.id, + method: request.method, + _meta: request.params?._meta, + ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, + ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, + ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, + requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), + signal: abortController.signal, + send: ((r, schemaOrOptions, maybeOptions) => { + const sendCodec = this._resolveOutboundCodec(r.method); + this._assertOutboundRequestInEra(sendCodec, r.method); + if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(sendCodec, r.method); + if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); + return sendRequest(r, validate, schemaOrOptions); + }), + notify: sendNotification + }, + http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 + }; + const ctx = this.buildContext(baseCtx, extra); + Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { + if (abortController.signal.aborted) return; + let encoded; + try { + encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec.encodeErrorCode(thrownCode), + message: error.message ?? "Internal error", + ...error["data"] !== void 0 && { data: error["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + handler(params); + } + /** + * Inbound-response dispatch. Subclass overrides MUST delegate unmatched + * traffic to `super._onresponse(response)` — an override that consumes + * only what it owns and falls through to base dispatch for everything + * else. + */ + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._progressHandlers.delete(messageId); + if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); + else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + request(request, schemaOrOptions, maybeOptions) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec, request.method); + if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); + return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); + } + /** + * The wire codec for this instance's negotiated era — the phase-2 truth: + * everything an established connection sends and receives resolves + * through it. Legacy until a version has been negotiated. + */ + _negotiatedWireCodec() { + return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + } + /** + * Protected accessor for the instance's negotiated wire codec, for role + * classes (Client/Server/McpServer) routing era-dependent behavior + * through the codec's function-only surface — `samplingResultVariant`, + * `outboundEnvelope`, `projectCallToolResult` — instead of branching on + * the protocol version themselves. + */ + _wireCodec() { + return this._negotiatedWireCodec(); + } + /** + * Outbound codec resolution: while the negotiated version is still unset + * (the negotiation window), lifecycle messages are bootstrap-pinned BY + * METHOD — they self-identify their era (`initialize` IS the legacy + * handshake, `server/discover` IS the modern probe). Once a version has + * been negotiated, the instance era is authoritative for everything — a + * negotiated session never re-routes a method onto the other era. + */ + _resolveOutboundCodec(method) { + if (this._negotiatedProtocolVersion === void 0) { + const pinned = bootstrapOutboundCodec(method); + if (pinned) return pinned; + } + return this._negotiatedWireCodec(); + } + /** + * Era gate for outbound requests — deletions are physical in BOTH + * directions: sending a spec method that the resolved era does not define + * dies locally with a typed error before anything reaches the transport. + * Methods outside the spec universe are consumer-owned extension methods + * and stay era-blind. + */ + _assertOutboundRequestInEra(codec, method) { + if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method, + era: codec.era + }); + } + /** + * Sends a request and waits for a response, using the provided schema for + * validation instead of the era registry's method-keyed entry. + * + * This is the internal implementation used by SDK methods whose result + * schema cannot be expressed as a method-keyed registry entry — the one + * surviving case is `server.createMessage`, whose result schema depends + * on the REQUEST params (tools vs no tools) — and by callers passing + * explicit compatibility schemas. Spec methods are still era-gated here: + * an explicit schema never smuggles a deleted method onto the wire. + */ + _requestWithSchema(request, resultSchema, options) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); + } + /** + * The request funnel proper, keyed by the resolved era codec: the codec + * owns result decoding (raw-first `resultType` discrimination — V-1 — + * and the era's lift posture) before the schema validation step. + */ + _requestWithSchemaViaCodec(codec, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error) { + earlyReject(error); + return; + } + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; + const messageId = this._requestMessageId++; + cleanupMessageId = messageId; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta, + progressToken: messageId + } + }; + } + const outbound = this._envelopeOutbound(jsonrpcRequest); + let responseReceived = false; + const cancel = (reason) => { + if (responseReceived) return; + this._progressHandlers.delete(messageId); + if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }), { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); + else requestAbort.abort(); + reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + responseReceived = true; + if (response instanceof Error) return reject(response); + let decoded; + try { + decoded = codec.decodeResult(request.method, response.result); + } catch (error) { + return reject(error instanceof Error ? error : new Error(String(error))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { + method: request.method, + params + }, resultSchema, legOptions) + }; + return resolve(this._resolveNonCompleteResult(decoded, flow)); + } + const result = decoded.result; + validateStandardSchema(resultSchema, result).then((parseResult) => { + if (parseResult.success) resolve(parseResult.data); + else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); + }, reject); + }); + onAbort = () => cancel(options?.signal?.reason); + options?.signal?.addEventListener("abort", onAbort, { once: true }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + this._transport.send(outbound, { + relatedRequestId, + resumptionToken, + onresumptiontoken, + headers, + requestSignal: requestAbort?.signal + }).catch((error) => { + this._progressHandlers.delete(messageId); + reject(error); + }); + }).finally(() => { + if (onAbort) options?.signal?.removeEventListener("abort", onAbort); + if (cleanupMessageId !== void 0) { + this._responseHandlers.delete(cleanupMessageId); + this._cleanupTimeout(cleanupMessageId); + } + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); + } + /** + * The notification funnel proper, keyed by the resolved era codec — + * direct sends and related notifications (`ctx.mcpReq.notify`) alike + * resolve through the instance's negotiated era at send time. + */ + async _notificationViaCodec(codec, notification, options) { + if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method: notification.method, + era: codec.era + }); + this.assertNotificationCapability(notification.method); + const jsonrpcNotification = this._envelopeOutbound({ + jsonrpc: "2.0", + ...notification + }); + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); + }); + return; + } + await this._transport.send(jsonrpcNotification, options); + } + setRequestHandler(method, schemasOrHandler, maybeHandler) { + this.assertRequestHandlerCapability(method); + let stored; + if (typeof schemasOrHandler === "function") { + if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); + stored = (request, ctx) => { + const dispatchCodec = this._negotiatedWireCodec(); + let outcome = dispatchCodec.validateRequest(method, request); + if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value, ctx)); + }; + } else if (maybeHandler) stored = async (request, ctx) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); + return maybeHandler(parsed.data, ctx); + }; + else throw new TypeError("setRequestHandler: handler is required"); + this._requestHandlers.set(method, this._wrapHandler(method, stored)); + } + /** + * Hook for subclasses to wrap a registered request handler with role-specific + * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` + * validates `elicitation/create` mode and result). Runs for both the 2-arg and + * 3-arg registration paths. The default implementation is identity. + * + * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. + */ + _wrapHandler(_method, handler) { + return handler; + } + /** + * Hook for subclasses to supply the implementation identity the 2026-era + * encode seam stamps into outbound result `_meta` under + * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD + * identify themselves on every response). The default is `undefined` — no + * stamp. Only `Server` overrides this: the key identifies the software + * producing a response, and the 2025-era codec never stamps anything + * regardless (the never-stamp guarantee). + */ + _outboundServerInfo() {} + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + setNotificationHandler(method, schemasOrHandler, maybeHandler) { + if (typeof schemasOrHandler === "function") { + if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); + this._notificationHandlers.set(method, (notification, codec) => { + const outcome = codec.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value)); + }); + return; + } + if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); + this._notificationHandlers.set(method, async (notification) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); + await maybeHandler(parsed.data, notification); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +}; +function isPlainObject$1(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { + ...baseValue, + ...addValue + } : addValue; + } + return result; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredEngine.ts +function src_CX2iR2pK_isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** +* Splits a retried request's `inputResponses` map into the BARE response +* entries the spec defines and everything else. The spec's embedded responses +* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or +* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some +* peers emit) is never accepted as a response — its key is recorded so the +* handler can re-issue the corresponding input request. +*/ +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +/** +* Builds the manual-mode {@linkcode InputRequiredResult} value from the +* codec's decoded payload — what an `allowInputRequired: true` caller +* receives instead of the auto-fulfilled complete result. +*/ +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} + +//#endregion +//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js +/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/ +var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + /** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + /** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse; + /** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + function parse(string) { + if (!string) throw new TypeError("argument string is required"); + var header = typeof string === "object" ? getcontenttype(string) : string; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + /** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + /** + * Class to represent a content type. + * @private + */ + function ContentType(type) { + this.parameters = Object.create(null); + this.type = type; + } +})); + +//#endregion +//#region ../core-internal/src/shared/mediaType.ts +var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); +/** +* Extracts the media type (the lowercased `type/subtype` pair, without +* parameters) from a raw `Content-Type` header value, or `undefined` when the +* header is missing or empty. +* +* Content-Type comparisons must use the parsed media type, never a substring +* search of the raw header: a value like `text/plain; a=application/json` +* contains the substring `application/json` but its media type is +* `text/plain`, and case variants or parameters make naive string comparison +* wrong in both directions. +* +* "Essence" is the WHATWG MIME Sniffing standard's term for the bare +* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); +* the Fetch standard's request classification is defined against it +* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). +* +* Parsing is RFC 9110 (`content-type` package) first. When the parameter +* section is malformed (`application/json;`, `application/json; charset=`), +* browsers and most HTTP stacks still derive the media type from the segment +* before the first `;` — the fallback matches that widely-implemented +* behavior, so a header whose media type is unambiguous is not rejected for +* a sloppy parameter section. +*/ +function src_CX2iR2pK_mediaTypeEssence(header) { + if (!header) return; + try { + return import_content_type.parse(header).type; + } catch { + const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); + if (essence === "" || header.slice(essence.length).includes(",")) return; + return essence; + } +} +/** +* Whether a raw `Content-Type` header value denotes `application/json`. +* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed +* parameter sections do not reject a header whose media type is unambiguously +* `application/json` (see `mediaTypeEssence` for the exact grammar). +*/ +function src_CX2iR2pK_isJsonContentType(header) { + if (header === "application/json") return true; + return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; +} + +//#endregion +//#region ../core-internal/src/shared/metadataUtils.ts +/** +* Utilities for working with {@linkcode BaseMetadata} objects. +*/ +/** +* Gets the display name for an object with {@linkcode BaseMetadata}. +* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` +* For other objects: `title` → `name` +* This implements the spec requirement: "if no title is provided, name should be used for display purposes" +*/ +function getDisplayName(metadata) { + if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; + if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; + return metadata.name; +} + +//#endregion +//#region ../core-internal/src/shared/stdio.ts +const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; +/** +* Buffers a continuous stdio stream into discrete JSON-RPC messages. +*/ +var ReadBuffer = class { + _buffer; + _maxBufferSize; + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; + } + append(chunk) { + if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + while (this._buffer) { + const index = this._buffer.indexOf("\n"); + if (index === -1) return null; + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + try { + return deserializeMessage(line); + } catch (error) { + if (error instanceof SyntaxError) continue; + throw error; + } + } + return null; + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +//#endregion +//#region ../core-internal/src/shared/toolNameValidation.ts +/** +* Tool name validation utilities according to SEP: Specify Format for Tool Names +* +* Tool names SHOULD be between 1 and 128 characters in length (inclusive). +* Tool names are case-sensitive. +* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits +* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). +* Tool names SHOULD NOT contain spaces, commas, or other special characters. +* +* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} +*/ +/** +* Regular expression for valid tool names according to SEP-986 specification +*/ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** +* Validates a tool name according to the SEP specification +* @param name - The tool name to validate +* @returns An object containing validation result and any warnings +*/ +function validateToolName(name) { + const warnings = []; + if (name.length === 0) return { + isValid: false, + warnings: ["Tool name cannot be empty"] + }; + if (name.length > 128) return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); + if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); + if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); + warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** +* Issues warnings for non-conforming tool names +* @param name - The tool name that triggered the warnings +* @param warnings - Array of warning messages +*/ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) console.warn(` - ${warning}`); + console.warn("Tool registration will proceed, but this may cause compatibility issues."); + console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); + console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); + } +} +/** +* Validates a tool name and issues warnings for non-conforming names +* @param name - The tool name to validate +* @returns `true` if the name is valid, `false` otherwise +*/ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + issueToolNameWarning(name, result.warnings); + return result.isValid; +} + +//#endregion +//#region ../core-internal/src/shared/transport.ts +/** +* Normalizes `HeadersInit` to a plain `Record` for manipulation. +* Handles `Headers` objects, arrays of tuples, and plain objects. +*/ +function normalizeHeaders(headers) { + if (!headers) return {}; + if (headers instanceof Headers) return Object.fromEntries(headers.entries()); + if (Array.isArray(headers)) return Object.fromEntries(headers); + return { ...headers }; +} +/** +* Creates a fetch function that includes base `RequestInit` options. +* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. +* +* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) +* @param baseInit - The base `RequestInit` to merge with each request +* @returns A wrapped fetch function that merges base options with call-specific options +*/ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url, init) => { + return baseFetch(url, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} + +//#endregion +//#region ../core-internal/src/shared/uriTemplate.ts +const MAX_TEMPLATE_LENGTH = 1e6; +const MAX_VARIABLE_LENGTH = 1e6; +const MAX_TEMPLATE_EXPRESSIONS = 1e4; +const MAX_REGEX_LENGTH = 1e6; +var src_CX2iR2pK_UriTemplate = class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like `{foo}` or `{?bar}`. + */ + static isTemplate(str) { + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + template; + parts; + get variableNames() { + return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ""; + let i = 0; + let expressionCount = 0; + while (i < template.length) if (template[i] === "{") { + if (currentText) { + parts.push(currentText); + currentText = ""; + } + const end = template.indexOf("}", i); + if (end === -1) throw new Error("Unclosed template expression"); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes("*"); + const names = this.getNames(expr); + const name = names[0]; + for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + parts.push({ + name, + operator, + names, + exploded + }); + i = end + 1; + } else { + currentText += template[i]; + i++; + } + if (currentText) parts.push(currentText); + return parts; + } + getOperator(expr) { + return [ + "+", + "#", + ".", + "/", + "?", + "&" + ].find((op) => expr.startsWith(op)) || ""; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); + if (operator === "+" || operator === "#") return encodeURI(value); + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === "?" || part.operator === "&") { + const pairs = part.names.map((name) => { + const value$1 = variables[name]; + if (value$1 === void 0) return ""; + return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; + }).filter((pair) => pair.length > 0); + if (pairs.length === 0) return ""; + return (part.operator === "?" ? "?" : "&") + pairs.join("&"); + } + if (part.names.length > 1) { + const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); + if (values.length === 0) return ""; + return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); + } + const value = variables[part.name]; + if (value === void 0) return ""; + const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); + switch (part.operator) { + case "": return encoded.join(","); + case "+": return encoded.join(","); + case "#": return "#" + encoded.join(","); + case ".": return "." + encoded.join("."); + case "/": return "/" + encoded.join("/"); + default: return encoded.join(","); + } + } + expand(variables) { + let result = ""; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === "string") { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) continue; + result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; + if (part.operator === "?" || part.operator === "&") hasQueryParam = true; + } + return result; + } + escapeRegExp(str) { + return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); + } + partToRegExp(part) { + const patterns = []; + for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + if (part.operator === "?" || part.operator === "&") { + for (let i = 0; i < part.names.length; i++) { + const name$1 = part.names[i]; + const prefix = i === 0 ? "\\" + part.operator : "&"; + patterns.push({ + pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", + name: name$1 + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case "": + pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; + break; + case "+": + case "#": + pattern = "(.+)"; + break; + case ".": + pattern = String.raw`\.([^/,]+)`; + break; + case "/": + pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); + break; + default: pattern = "([^/]+)"; + } + patterns.push({ + pattern, + name + }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); + let pattern = "^"; + const names = []; + for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ + name, + exploded: part.exploded + }); + } + } + pattern += "$"; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) return null; + const result = {}; + for (const [i, name_] of names.entries()) { + const { name, exploded } = name_; + const value = match[i + 1]; + const cleanName = name.replace("*", ""); + result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; + } + return result; + } +}; + +//#endregion +//#region ../core-internal/src/util/inMemory.ts +/** +* In-memory transport for creating clients and servers that talk to each other within the same process. +* +* Intended for testing and development. For production in-process connections, use +* `StreamableHTTPClientTransport` against a local server URL. +*/ +var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { + _otherTransport; + _messageQueue = []; + _closed = false; + onclose; + onerror; + onmessage; + sessionId; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + if (this._closed) return; + this._closed = true; + const other = this._otherTransport; + this._otherTransport = void 0; + try { + await other?.close(); + } finally { + this.onclose?.(); + } + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + else this._otherTransport._messageQueue.push({ + message, + extra: { authInfo: options?.authInfo } + }); + } +}; + +//#endregion +//#region ../core-internal/src/util/zodCompat.ts +/** +* Zod-specific helpers for the v1-compat raw-shape shorthand on +* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so +* that file stays library-agnostic per the Standard Schema spec. +*/ +function isZodV4Schema(v) { + return typeof v === "object" && v !== null && "_zod" in v; +} +function looksLikeZodV3(v) { + return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; +} +/** +* Detects a "raw shape" — a plain object whose values are Zod field schemas, +* e.g. `{ name: z.string() }`. Powers the auto-wrap in +* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only +* Zod values are supported. +* +* @internal +*/ +function isZodRawShape(obj) { + if (typeof obj !== "object" || obj === null) return false; + if (isStandardSchema(obj)) return false; + const proto = Object.getPrototypeOf(obj); + if (proto !== Object.prototype && proto !== null) return false; + return Object.values(obj).every((v) => isZodV4Schema(v)); +} +/** +* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape +* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. +* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a +* uniform schema type; already-wrapped schemas pass through unchanged. +* +* @internal +*/ +function normalizeRawShapeSchema(schema) { + if (schema === void 0) return void 0; + if (isZodRawShape(schema)) return schemas_object(schema); + if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); + if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); + return schema; +} + +//#endregion +//#region ../core-internal/src/wire/preload.ts +/** +* Explicit warm-up entry for the lazy wire-schema layers. +* +* The per-revision wire schemas are built lazily: each era's schema set sits +* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the +* registry/codec lookup maps above those factories are memoized the same way. +* That laziness is the right default on process-per-invocation runtimes (CLI +* tools, dev servers), where module evaluation IS startup latency and most +* short-lived processes never validate a message on both eras. +* +* On platforms that bill request CPU but not module evaluation — isolate-based +* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: +* module-scope work runs during isolate warm-up outside any request, while +* lazy construction lands inside the first request's billed (and latency +* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move +* the one-time construction cost back to module scope by calling it at module +* scope themselves. The packages' own workerd shims already do this, so +* Workers deployments get eager construction automatically. +*/ +/** +* Eagerly builds every lazily-constructed wire-schema layer, so that no later +* validation pays schema-construction cost. +* +* Synchronous and idempotent: every layer is a memo, so the first call does +* all the work and subsequent calls return immediately. Reference identity is +* unaffected — this forces the same memos every lazy consumer pulls through. +* +* Call it at module scope on platforms that bill per-request CPU but not +* module evaluation (isolate-based edge/serverless runtimes), where deferring +* construction would move it into the first request of every fresh isolate: +* +* ```ts +* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — +* // each package bundles its own schema copy, so warm the one(s) you import. +* preloadSchemas(); // module scope — runs during isolate warm-up +* ``` +* +* On Node CLIs and other process-per-invocation runtimes, prefer the lazy +* default — there, module-scope construction is pure added boot latency. +*/ +function preloadSchemas() { + buildSchemas2025(); + buildSchemas2026(); + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} + +//#endregion +//#region ../core-internal/src/validators/fromJsonSchema.ts +/** +* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be +* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON +* Schema (e.g. from TypeBox, or hand-written) and want to register it without going +* through a Standard Schema library. +* +* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript +* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. +* +* @param schema - A JSON Schema object describing the expected shape +* @param validator - A validator provider. When importing `fromJsonSchema` from +* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate +* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). +* +* @example +* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" +* const inputSchema = fromJsonSchema<{ name: string }>( +* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, +* validator +* ); +* // Use with server.registerTool('greet', { inputSchema }, handler) +* ``` +*/ +function fromJsonSchema(schema, validator) { + const check = validator.getValidator(schema); + return { "~standard": { + version: 1, + vendor: "mcp", + jsonSchema: { + input: () => schema, + output: () => schema + }, + validate: (data) => { + const result = check(data); + return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; + } + } }; +} + +//#endregion + +//# sourceMappingURL=src-CX2iR2pK.mjs.map + + + +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = require_code$1(); + const scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = require_codegen(); + const code_1 = require_code$1(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const names = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = require_rules(); + const applicability_1 = require_applicability(); + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const code_1 = require_code(); + const errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a$1; + gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0;) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + const util_1 = require_util(); + const equal = require_fast_deep_equal(); + const traverse = require_json_schema_traverse(); + const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + const TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + const boolSchema_1 = require_boolSchema(); + const dataType_1 = require_dataType(); + const applicability_1 = require_applicability(); + const dataType_2 = require_dataType(); + const defaults_1 = require_defaults(); + const keyword_1 = require_keyword(); + const subschema_1 = require_subschema(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + const codegen_1 = require_codegen(); + const validation_error_1 = require_validation_error(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { "$data": { + "type": "string", + "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] + } }, + "additionalProperties": false + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** @type {(value: string) => boolean} */ + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + /** @type {(value: string) => boolean} */ + const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + /** + * @param {Array} input + * @returns {string} + */ + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + /** + * @typedef {Object} GetIPV6Result + * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. + * @property {string} address - The parsed IPv6 address. + * @property {string} [zone] - The zone identifier, if present. + */ + /** + * @param {string} value + * @returns {boolean} + */ + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + /** + * @param {Array} buffer + * @returns {boolean} + */ + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + /** + * @param {Array} buffer + * @param {Array} address + * @param {GetIPV6Result} output + * @returns {boolean} + */ + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") address.push(hex); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + /** + * @param {string} input + * @returns {GetIPV6Result} + */ + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + /** @type {Array} */ + const address = []; + /** @type {Array} */ + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + /** + * @typedef {Object} NormalizeIPv6Result + * @property {string} host - The normalized host. + * @property {string} [escapedHost] - The escaped host. + * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. + */ + /** + * @param {string} host + * @returns {NormalizeIPv6Result} + */ + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + /** + * @param {string} str + * @param {string} token + * @returns {number} + */ + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + /** + * @param {string} path + * @returns {string} + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + /** + * @param {import('../types/index').URIComponent} component + * @param {boolean} esc + * @returns {import('../types/index').URIComponent} + */ + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) component.scheme = func(component.scheme); + if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); + if (component.host !== void 0) component.host = func(component.host); + if (component.path !== void 0) component.path = func(component.path); + if (component.query !== void 0) component.query = func(component.query); + if (component.fragment !== void 0) component.fragment = func(component.fragment); + return component; + } + /** + * @param {import('../types/index').URIComponent} component + * @returns {string|undefined} + */ + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = component.host; + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { isUUID } = require_utils(); + const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + const supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + /** @typedef {supportedSchemeNames[number]} SchemeName */ + /** + * @param {string} name + * @returns {name is SchemeName} + */ + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + /** + * @callback SchemeFn + * @param {import('../types/index').URIComponent} component + * @param {import('../types/index').Options} options + * @returns {import('../types/index').URIComponent} + */ + /** + * @typedef {Object} SchemeHandler + * @property {SchemeName} scheme - The scheme name. + * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. + * @property {SchemeFn} parse - Function to parse the URI component for this scheme. + * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. + * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. + * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. + * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. + */ + /** + * @param {import('../types/index').URIComponent} wsComponent + * @returns {boolean} + */ + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + /** @type {SchemeFn} */ + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + /** @type {SchemeFn} */ + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + /** @type {SchemeFn} */ + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + /** @type {SchemeFn} */ + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + /** @type {SchemeFn} */ + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + /** @type {SchemeFn} */ + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + const http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + const https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + const ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + const wss = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }; + const urn = { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }; + const urnuuid = { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + }; + const SCHEMES = { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + }; + Object.setPrototypeOf(SCHEMES, null); + /** + * @param {string|undefined} scheme + * @returns {SchemeHandler|undefined} + */ + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + /** + * @template {import('./types/index').URIComponent|string} T + * @param {T} uri + * @param {import('./types/index').Options} [options] + * @returns {T} + */ + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse(uri, options), options); + else if (typeof uri === "object") uri = parse(serialize(uri, options), options); + return uri; + } + /** + * @param {string} baseURI + * @param {string} relativeURI + * @param {import('./types/index').Options} [options] + * @returns {string} + */ + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + /** + * @param {import ('./types/index').URIComponent} base + * @param {import ('./types/index').URIComponent} relative + * @param {import('./types/index').Options} [options] + * @param {boolean} [skipNormalization=false] + * @returns {import ('./types/index').URIComponent} + */ + function resolveComponent(base, relative, options, skipNormalization) { + /** @type {import('./types/index').URIComponent} */ + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); + relative = parse(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + /** + * @param {import ('./types/index').URIComponent|string} uriA + * @param {import ('./types/index').URIComponent|string} uriB + * @param {import ('./types/index').Options} options + * @returns {boolean} + */ + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { + ...options, + skipEscape: true + }); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + /** + * @param {Readonly} cmpts + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = unescape(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns + */ + function parse(uri, opts) { + const options = Object.assign({}, opts); + /** @type {import('./types/index').URIComponent} */ + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = unescape(parsed.host); + } + if (parsed.path) parsed.path = escape(unescape(parsed.path)); + if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return parsed; + } + const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + const validation_error_1 = require_validation_error(); + const ref_error_1 = require_ref_error(); + const rules_1 = require_rules(); + const compile_1 = require_compile(); + const codegen_2 = require_codegen(); + const resolve_1 = require_resolve(); + const dataType_1 = require_dataType(); + const util_1 = require_util(); + const $dataRefSchema = require_data(); + const uri_1 = require_uri(); + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + const removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: "\"nullable\" keyword is supported by default.", + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: "\"uniqueItems\" keyword is always validated.", + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + const MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + const ref_error_1 = require_ref_error(); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const util_1 = require_util(); + const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const id_1 = require_id(); + const ref_1 = require_ref(); + const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const ucs2length_1 = require_ucs2length(); + const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const util_1 = require_util(); + const codegen_1 = require_codegen(); + const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dataType_1 = require_dataType(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const limitNumber_1 = require_limitNumber(); + const multipleOf_1 = require_multipleOf(); + const limitLength_1 = require_limitLength(); + const pattern_1 = require_pattern(); + const limitProperties_1 = require_limitProperties(); + const required_1 = require_required(); + const limitItems_1 = require_limitItems(); + const uniqueItems_1 = require_uniqueItems(); + const const_1 = require_const(); + const enum_1 = require_enum(); + const validation = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; + exports.default = validation; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const items_1 = require_items(); + const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const additionalItems_1 = require_additionalItems(); + const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const util_1 = require_util(); + const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const validate_1 = require_validate(); + const code_1 = require_code(); + const util_1 = require_util(); + const additionalProperties_1 = require_additionalProperties(); + const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const util_2 = require_util(); + const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const additionalItems_1 = require_additionalItems(); + const prefixItems_1 = require_prefixItems(); + const items_1 = require_items(); + const items2020_1 = require_items2020(); + const contains_1 = require_contains(); + const dependencies_1 = require_dependencies(); + const propertyNames_1 = require_propertyNames(); + const additionalProperties_1 = require_additionalProperties(); + const properties_1 = require_properties(); + const patternProperties_1 = require_patternProperties(); + const not_1 = require_not(); + const anyOf_1 = require_anyOf(); + const oneOf_1 = require_oneOf(); + const allOf_1 = require_allOf(); + const if_1 = require_if(); + const thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$2().default]; + exports.default = format; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const types_1 = require_types(); + const compile_1 = require_compile(); + const ref_error_1 = require_ref_error(); + const util_1 = require_util(); + const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const discriminator_1 = require_discriminator(); + const draft7MetaSchema = require_json_schema_draft_07(); + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js +var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicAnchor = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema) + }; + function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); + } + exports.dynamicAnchor = dynamicAnchor; + function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js +var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicRef = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema) + }; + function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) _dynamicRef(); + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } else _callRef(it.validateName, valid)(); + } + function _callRef(validate, valid) { + return valid ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) : () => (0, ref_1.callRef)(cxt, validate); + } + } + exports.dynamicRef = dynamicRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js +var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const util_1 = require_util(); + const def = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js +var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicRef_1 = require_dynamicRef(); + const def = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js +var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const dynamicRef_1 = require_dynamicRef(); + const recursiveAnchor_1 = require_recursiveAnchor(); + const recursiveRef_1 = require_recursiveRef(); + const dynamic = [ + dynamicAnchor_1.default, + dynamicRef_1.default, + recursiveAnchor_1.default, + recursiveRef_1.default + ]; + exports.default = dynamic; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js +var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js +var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js +var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js +var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependentRequired_1 = require_dependentRequired(); + const dependentSchemas_1 = require_dependentSchemas(); + const limitContains_1 = require_limitContains(); + const next = [ + dependentRequired_1.default, + dependentSchemas_1.default, + limitContains_1.default + ]; + exports.default = next; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js +var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const def = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` + }, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + it.props = true; + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); + return (0, codegen_1.and)(...ps); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js +var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) return; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._)`${len} > ${items}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ + keyword: "unevaluatedItems", + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js +var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const unevaluatedProperties_1 = require_unevaluatedProperties(); + const unevaluatedItems_1 = require_unevaluatedItems(); + const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; + exports.default = unevaluated; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "meta/validation#/$defs/stringArray" }] } + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, + "$recursiveAnchor": true, + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": { "$recursiveRef": "#" }, + "unevaluatedItems": { "$recursiveRef": "#" }, + "items": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "#/$defs/schemaArray" }] }, + "contains": { "$recursiveRef": "#" }, + "additionalProperties": { "$recursiveRef": "#" }, + "unevaluatedProperties": { "$recursiveRef": "#" }, + "properties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" } + }, + "propertyNames": { "$recursiveRef": "#" }, + "if": { "$recursiveRef": "#" }, + "then": { "$recursiveRef": "#" }, + "else": { "$recursiveRef": "#" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$recursiveRef": "#" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$recursiveRef": "#" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json +var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, + "$recursiveAnchor": true, + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json +var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json +var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, + "$recursiveAnchor": true, + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js +var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema$1(); + const applicator = require_applicator$1(); + const content = require_content$1(); + const core = require_core$1(); + const format = require_format(); + const metadata = require_meta_data$1(); + const validation = require_validation$1(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2019($data) { + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2019; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js +var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const discriminator_1 = require_discriminator(); + const json_schema_2019_09_1 = require_json_schema_2019_09(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; + var Ajv2019 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2019 = Ajv2019; + module.exports = exports = Ajv2019; + module.exports.Ajv2019 = Ajv2019; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2019; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js +var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default + ]; + exports.default = draft2020Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json +var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/unevaluated" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format-annotation" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { "anyOf": [{ "$dynamicRef": "#meta" }, { "$ref": "meta/validation#/$defs/stringArray" }] }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, + "$dynamicAnchor": "meta", + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": { "$ref": "#/$defs/schemaArray" }, + "items": { "$dynamicRef": "#meta" }, + "contains": { "$dynamicRef": "#meta" }, + "additionalProperties": { "$dynamicRef": "#meta" }, + "properties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "propertyNames": { "$dynamicRef": "#meta" }, + "if": { "$dynamicRef": "#meta" }, + "then": { "$dynamicRef": "#meta" }, + "else": { "$dynamicRef": "#meta" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$dynamicRef": "#meta" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$dynamicRef": "#meta" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json +var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json +var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json +var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, + "$dynamicAnchor": "meta", + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { "$ref": "#/$defs/uriString" }, + "$ref": { "$ref": "#/$defs/uriReferenceString" }, + "$anchor": { "$ref": "#/$defs/anchorString" }, + "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, + "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, + "$vocabulary": { + "type": "object", + "propertyNames": { "$ref": "#/$defs/uriString" }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" } + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json +var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json +var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json +var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, + "$dynamicAnchor": "meta", + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js +var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema(); + const applicator = require_applicator(); + const unevaluated = require_unevaluated(); + const content = require_content(); + const core = require_core(); + const format = require_format_annotation(); + const metadata = require_meta_data(); + const validation = require_validation(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2020; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js +var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; + const core_1 = require_core$3(); + const draft2020_1 = require_draft2020(); + const discriminator_1 = require_discriminator(); + const json_schema_2020_12_1 = require_json_schema_2020_12(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + var Ajv2020 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2020 = Ajv2020; + module.exports = exports = Ajv2020; + module.exports.Ajv2020 = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + byte, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + const DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date(str) { + const matches = DATE.exec(str); + if (!matches) return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + const DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + const NOT_URI_FRAGMENT = /\/|:/; + const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + const MIN_INT32 = -(2 ** 31); + const MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + const Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + const ajv_1 = require_ajv(); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const formats_1 = require_formats(); + const limit_1 = require_limit(); + const codegen_1 = require_codegen(); + const fullName = new codegen_1.Name("fullFormats"); + const fastName = new codegen_1.Name("fastFormats"); + const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); + +//#endregion +//#region ../core-internal/src/validators/ajvProvider.ts +var import_ajv = require_ajv(); +var import__2019 = require__2019(); +var import__2020 = require__2020(); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ +const ajvProvider_CEoC_sr_addFormats = import_dist.default; +function createDefaultAjvInstance(engineClass) { + const ajv = new engineClass({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + ajvProvider_CEoC_sr_addFormats(ajv); + return ajv; +} +/** +* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` +* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). +* +* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` +* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class +* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv +* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching +* v1's default engine), while the cfworker provider ignores them per spec. +* Schemas declaring any other `$schema` are +* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate +* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type +* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 +* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and +* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would +* silently downgrade dialect. +* +* @example Use with default configuration +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" +* const validator = new AjvJsonSchemaValidator(); +* ``` +* +* @example Use with a custom AJV instance +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +* +* @example Register ajv-formats +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +*/ +var AjvJsonSchemaValidator = class { + _ajv; + /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ + _ajvDraft7; + /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ + _ajv2019; + /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ + _userAjv; + /** + * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is + * used for **every** schema regardless of its declared `$schema` (the caller owns dialect + * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, + * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. + */ + constructor(ajv) { + this._userAjv = ajv !== void 0; + this._ajv = ajv; + } + /** The underlying 2020-12 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); + } + /** + * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for + * every schema — do not second-guess by `$schema` (bring-your-own-validator means + * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → + * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. + */ + _engineFor(schema) { + if (this._userAjv) return this.ajv; + const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); + if (dialect === "2020-12") return this.ajv; + if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); + return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); + } + getValidator(schema) { + const engine = this._engineFor(schema); + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); + return (input) => { + return ajvValidator(input) ? { + valid: true, + data: input, + errorMessage: void 0 + } : { + valid: false, + data: void 0, + errorMessage: engine.errorsText(ajvValidator.errors) + }; + }; + } +}; +/** +* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. +* The full v1-equivalent construction is: +* +* ```ts +* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* new AjvJsonSchemaValidator(ajv); +* ``` +* +* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque +* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` +* validation that the v1 default had). +* +* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream +* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own +* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. +*/ +const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; + +//#endregion + +//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map + + + + + + + + +//#region src/server/completable.ts +const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); +/** +* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. +* +* @example +* ```ts source="./completable.examples.ts#completable_basicUsage" +* server.registerPrompt( +* 'review-code', +* { +* title: 'Code Review', +* argsSchema: z.object({ +* language: completable(z.string().describe('Programming language'), value => +* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) +* ) +* }) +* }, +* ({ language }) => ({ +* messages: [ +* { +* role: 'user' as const, +* content: { +* type: 'text' as const, +* text: `Review this ${language} code.` +* } +* } +* ] +* }) +* ); +* ``` +* +* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions +*/ +function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** +* Checks if a schema is completable (has completion metadata). +*/ +function isCompletable(schema) { + return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; +} +/** +* Gets the completer callback from a completable schema, if it exists. +*/ +function getCompleter(schema) { + return schema[COMPLETABLE_SYMBOL]?.complete; +} + +//#endregion +//#region src/server/sseKeepAlive.ts +/** Default interval between SSE keep-alive comment frames. */ +const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; +const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); +/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ +function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { + if (!Number.isFinite(intervalMs) || intervalMs < 1) return; + const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); + timer.unref?.(); + return timer; +} + +//#endregion +//#region src/server/serverEventBus.ts +/** +* A `ServerEventBus` backed by an in-process listener set. +* +* `publish()` delivers synchronously to the live listener set (a listener +* unsubscribing itself mid-dispatch is safe; the entry's listen-router +* listeners never unsubscribe peers). A throwing listener does not stop +* delivery to the others. +*/ +var mcp_DXXb3Vv3_InMemoryServerEventBus = class { + _listeners = /* @__PURE__ */ new Set(); + /** + * @param onerror - Optional callback for errors thrown by listeners + * during dispatch. + */ + constructor(onerror) { + this.onerror = onerror; + } + publish(event) { + for (const listener of this._listeners) try { + listener(event); + } catch (error) { + this.onerror?.(error instanceof Error ? error : new Error(String(error))); + } + } + subscribe(listener) { + this._listeners.add(listener); + let live = true; + return () => { + if (!live) return; + live = false; + this._listeners.delete(listener); + }; + } + /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ + get listenerCount() { + return this._listeners.size; + } +}; +/** Build a {@linkcode ServerNotifier} over a bus. */ +function mcp_DXXb3Vv3_createServerNotifier(bus) { + return { + toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), + promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), + resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), + resourceUpdated: (uri) => bus.publish({ + kind: "resource_updated", + uri + }) + }; +} +/** +* Whether a `subscriptions/listen` filter accepts a given change event. +* +* Pure: no I/O, no mutation. The filter governs ONLY the four +* subscription-gated change types — non-gated notifications never reach the +* bus and are not modeled here. +* +* `resource_updated` matches only when `resourceSubscriptions` is present and +* contains the event's URI exactly (per the spec: "for these resource URIs"). +*/ +function listenFilterAccepts(filter, event) { + switch (event.kind) { + case "tools_list_changed": return filter.toolsListChanged === true; + case "prompts_list_changed": return filter.promptsListChanged === true; + case "resources_list_changed": return filter.resourcesListChanged === true; + case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); + } +} +/** +* The honored subset of a requested filter: keeps only the fields the client +* explicitly opted in to (drops `false` and absent fields), narrowed against +* the server's declared capabilities when supplied. The serving entry sends +* this back in `notifications/subscriptions/acknowledged` so the ack reflects +* what the server can actually deliver. +* +* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` +* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. +* - `resourceSubscriptions` is honored only when +* `capabilities.resources.subscribe` is advertised. +* +* `capabilities` is optional on this pure helper for test convenience only — +* both wired routers REQUIRE capabilities at the call site (the HTTP router's +* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws +* before `setServerCapabilities()` was called), so the fail-open +* `undefined → honor everything` branch is never reachable on a wired entry. +*/ +function honoredSubset(requested, capabilities) { + const honored = {}; + const allow = (bit) => capabilities === void 0 || bit === true; + if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; + if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; + if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; + if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; + return honored; +} +/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ +function serverEventToNotification(event) { + switch (event.kind) { + case "tools_list_changed": return { method: "notifications/tools/list_changed" }; + case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; + case "resources_list_changed": return { method: "notifications/resources/list_changed" }; + case "resource_updated": return { + method: "notifications/resources/updated", + params: { uri: event.uri } + }; + } +} + +//#endregion +//#region src/server/listenRouter.ts +/** Default capacity guard: refuse a new subscription when this many are already open. */ +const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; +function jsonRpcError(id, code, message) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message + }, + id + }, { status: 200 }); +} +/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ +function stampSubscriptionId(notification, subscriptionId) { + return { + method: notification.method, + params: { + ...notification.params, + _meta: { + ...notification.params?._meta, + [SUBSCRIPTION_ID_META_KEY]: subscriptionId + } + } + }; +} +/** +* Read the requested filter off a `subscriptions/listen` request body. +* Returns the validated filter, or `undefined` when `params.notifications` +* is absent or fails the schema (the caller answers `-32602` — the spec +* marks `notifications` REQUIRED on the listen request). +*/ +function parseListenFilter(message) { + const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); + return outcome.ok ? outcome.value.params?.notifications : void 0; +} +function mcp_DXXb3Vv3_createListenRouter(options) { + const { bus, onerror } = options; + const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; + const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; + const open = /* @__PURE__ */ new Set(); + function serve(message, signal, capabilities, serverInfo) { + if (open.size >= maxSubscriptions) { + onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); + return jsonRpcError(message.id, -32603, "Subscription limit reached"); + } + const filter = parseListenFilter(message); + if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); + const honored = honoredSubset(filter, capabilities); + const subscriptionId = message.id; + const encoder = new TextEncoder(); + let controller; + let closed = false; + let unsubscribe; + let keepAliveTimer; + let abortCleanup; + const writeFrame = (frame) => { + if (closed) return; + try { + controller.enqueue(encoder.encode(frame)); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + }; + const writeNotification = (method, params) => { + writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + method, + params + })}\n\n`); + }; + const teardown = (graceful) => { + if (closed) return; + if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: subscriptionId, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: subscriptionId, + [SERVER_INFO_META_KEY]: serverInfo + } + } + })}\n\n`); + closed = true; + try { + unsubscribe?.(); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + abortCleanup?.(); + open.delete(teardown); + try { + controller.close(); + } catch {} + }; + const readable = new ReadableStream({ + start(streamController) { + controller = streamController; + const ack = stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, subscriptionId); + writeNotification(ack.method, ack.params); + unsubscribe = bus.subscribe((event) => { + if (closed || !listenFilterAccepts(honored, event)) return; + const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); + writeNotification(note.method, note.params); + }); + keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); + open.add(teardown); + }, + cancel() { + teardown(false); + } + }); + if (signal !== void 0) if (signal.aborted) teardown(false); + else { + const onAbort = () => teardown(false); + signal.addEventListener("abort", onAbort, { once: true }); + abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + return new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + }); + } + return { + serve, + closeAll() { + for (const teardown of open) teardown(true); + }, + get openCount() { + return open.size; + } + }; +} +const CHANGE_NOTIFICATION_METHODS = new Set([ + "notifications/tools/list_changed", + "notifications/prompts/list_changed", + "notifications/resources/list_changed", + "notifications/resources/updated" +]); +/** +* Per-connection listen state for the stdio entry. One instance is held by +* `serveStdio` for the connection lifetime; it routes inbound +* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound +* change notifications onto the active subscriptions. No bus — the long-lived +* pinned instance's existing `send*ListChanged()` calls feed straight into +* `routeOutbound()`. +*/ +var mcp_DXXb3Vv3_StdioListenRouter = class { + /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ + _subs = /* @__PURE__ */ new Map(); + /** + * The serving instance's declared capabilities. Filled in by the entry + * once the modern instance is constructed (the router is created before + * the instance exists), so the acknowledged filter is narrowed against + * what the server can actually deliver. + */ + _serverCapabilities; + /** + * The serving instance's identity, stamped onto the graceful-close + * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends + * `ResultMetaObject`). Handed over together with the capabilities. + */ + _serverInfo; + constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { + this._maxSubscriptions = _maxSubscriptions; + this._serverCapabilities = serverCapabilities; + this._serverInfo = serverInfo; + } + /** + * Record the serving instance's declared capabilities and identity once + * it has been constructed. Called by `serveStdio`'s connect path; + * subsequent `serve()` calls narrow the honored filter against the + * capabilities, and `teardownAll()` stamps the identity. + */ + setServerCapabilities(capabilities, serverInfo) { + this._serverCapabilities = capabilities; + if (serverInfo !== void 0) this._serverInfo = serverInfo; + } + /** Whether `id` is an active listen subscription on this connection. */ + has(id) { + return this._subs.has(id); + } + /** + * Serve one inbound `subscriptions/listen` request: registers the + * subscription and returns the stamped acknowledged notification (or, on + * capacity / params rejection, the in-band JSON-RPC error response). + * + * @throws when called before {@linkcode setServerCapabilities} (or the + * constructor) has supplied the serving instance's capabilities. Honoring a + * filter without knowing the server's advertised capabilities would fail + * open (deliver unadvertised types); the entry guarantees capabilities are + * set before any listen request is routed here. + */ + serve(message) { + if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); + if (this._subs.size >= this._maxSubscriptions) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32603, + message: "Subscription limit reached" + } + }; + const filter = parseListenFilter(message); + if (filter === void 0) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" + } + }; + const honored = honoredSubset(filter, this._serverCapabilities); + this._subs.set(message.id, honored); + return stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, message.id); + } + /** + * Tear down one subscription (inbound `notifications/cancelled`). Returns + * `true` when a subscription was removed. After this call NOTHING further + * is delivered for that subscription id (the post-cancel hardening). + */ + cancel(id) { + return this._subs.delete(id); + } + /** + * Route an outbound notification through the active subscriptions. + * + * - For a subscription-gated change notification, returns one stamped copy + * per subscription that opted in to it (an empty array means it is + * dropped — the modern era never delivers an un-requested change type). + * - For any other outbound message, returns `'passthrough'` (the entry + * forwards it as-is). + */ + routeOutbound(message) { + if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; + const uriParam = message.params?.["uri"]; + const uri = typeof uriParam === "string" ? uriParam : void 0; + const event = notificationToServerEvent(message.method, uri); + const out = []; + for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ + method: message.method, + params: message.params ?? {} + }, subscriptionId)); + return out; + } + /** + * Server-side graceful teardown of every active subscription: returns the + * empty `subscriptions/listen` JSON-RPC result for each subscription id — + * the spec's graceful-close signal, `_meta` carrying the subscription id + * and the serving instance's identity — for the entry to emit before + * closing the wire. Clears the set so nothing further is delivered. + */ + teardownAll() { + const out = []; + for (const id of this._subs.keys()) out.push({ + jsonrpc: "2.0", + id, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: id, + ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } + } + } + }); + this._subs.clear(); + return out; + } +}; +function notificationToServerEvent(method, uri) { + switch (method) { + case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; + case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; + case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; + default: return { + kind: "resource_updated", + uri: uri ?? "" + }; + } +} + +//#endregion +//#region src/server/legacyInputRequiredShim.ts +/** +* Default handler re-entries per originating request — tighter than the +* client driver's 10 because the shim holds a live wire request open. +*/ +const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; +/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ +const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; +/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ +function resolveLegacyShimOptions(options) { + if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); + if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); + return { + maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, + roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, + legacyShim: options?.legacyShim ?? true + }; +} +/** +* Validates one `inputRequests` entry: malformed or unknown kinds are server +* bugs and fail loudly on both eras. Shared by the modern seam's capability +* check and the shim's gate. +*/ +function coerceEmbeddedInputRequest(method, key, entry) { + if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); + const embedded = entry; + const required = requiredClientCapabilitiesForInputRequest(embedded); + if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); + return { + embedded, + required + }; +} +/** +* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 +* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a +* getRandomValues fallback for runtimes without `randomUUID`). +*/ +function syntheticElicitationId() { + const webCrypto = globalThis.crypto; + if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); + const bytes = new Uint8Array(16); + webCrypto.getRandomValues(bytes); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ +function legacyShimFailure(method, message) { + if (method === "tools/call") return { + content: [{ + type: "text", + text: message + }], + isError: true + }; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); +} +/** The fulfilment loop — see the module doc for the contract. */ +var LegacyInputRequiredShim = class { + constructor(_host) { + this._host = _host; + } + async fulfill(method, handler, request, ctx, firstResult) { + const { maxRounds, roundTimeoutMs } = this._host; + const outerSignal = ctx.mcpReq.signal; + let current = firstResult; + let round = 0; + while (true) { + round += 1; + if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); + const inputRequests = current.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const requestState = typeof current.requestState === "string" ? current.requestState : void 0; + if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + let responses; + if (hasInputRequests) { + const declared = this._host.resolvedClientCapabilities(ctx); + const coerced = []; + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); + if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); + coerced.push([key, embedded]); + } + const roundAbort = linkedRoundAbort(outerSignal); + try { + const legOptions = { + relatedRequestId: ctx.mcpReq.id, + timeout: roundTimeoutMs, + resetTimeoutOnProgress: true, + onprogress: () => {}, + signal: roundAbort.signal + }; + const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { + try { + return [key, await this._dispatchLeg(embedded, legOptions)]; + } catch (error) { + roundAbort.abort(error); + throw error; + } + })); + responses = Object.fromEntries(fulfilled); + } catch (error) { + if (outerSignal.aborted) throw error; + return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); + } finally { + roundAbort.dispose(); + } + } else await sleep((/* inlined export .C */250), outerSignal); + let ctxNext = { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + inputResponses: responses, + droppedInputResponseKeys: void 0, + requestState: requestStateAccessor(requestState) + } + }; + if (requestState !== void 0) { + const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); + if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); + } + const next = await handler(request, ctxNext); + if (!isInputRequiredResult(next)) return next; + current = next; + } + } + /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ + async _dispatchLeg(embedded, options) { + switch (embedded.method) { + case "elicitation/create": { + let params = embedded.params; + if (params.mode === "url" && params.elicitationId === void 0) params = { + ...params, + elicitationId: syntheticElicitationId() + }; + return await this._host.sendElicitation(params, options); + } + case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); + case "roots/list": return await this._host.listRoots(embedded.params, options); + } + } +}; + +//#endregion +//#region src/server/server.ts +/** +* The request methods whose 2026-07-28 result vocabulary includes +* `input_required` (the multi round-trip methods). Returning an +* input-required result from any other handler is a server bug. +*/ +const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ + "tools/call", + "prompts/get", + "resources/read" +]); +let writeClientIdentity; +let installDiscoverHandler; +let readServerIdentity; +/** +* Package-internal: backfills the connection-scoped client-identity fields of a +* per-request server instance from the request's validated `_meta` envelope, so the +* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} +* accessors keep answering on instances that never see an `initialize` handshake. +* Not public API. +*/ +function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { + writeClientIdentity(server, identity); +} +/** +* Package-internal: installs the modern-only `server/discover` handler on an instance +* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern +* revisions the entry serves appear in the instance's supported-versions list (so the +* discover advertisement and version-mismatch errors name them). Idempotent. +* Hand-constructed instances are unaffected: nothing else calls this, so they keep +* answering `-32601` unless their own supported-versions list opts into a modern +* revision. Not public API. +*/ +function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { + installDiscoverHandler(server, servedModernVersions); +} +/** +* Package-internal: the instance's implementation identity, for the serving +* entries to stamp onto entry-built results (the `subscriptions/listen` +* graceful-close result — built outside the encode seam, but the spec's +* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries +* the serverInfo SHOULD like every other result). Not public API. +*/ +function mcp_DXXb3Vv3_serverIdentityOf(server) { + return readServerIdentity(server); +} +/** +* An MCP server on top of a pluggable transport. +* +* This server will automatically respond to the initialization flow as initiated from the client. +* +* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. +*/ +var Server = class extends Protocol { + _clientCapabilities; + _clientVersion; + static { + writeClientIdentity = (server, identity) => { + if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; + if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; + }; + installDiscoverHandler = (server, servedModernVersions) => { + const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); + if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; + server.setRequestHandler("server/discover", () => server._ondiscover()); + }; + readServerIdentity = (server) => server._serverInfo; + } + _capabilities; + _instructions; + _jsonSchemaValidator; + _cacheHints; + _requestStateVerify; + _inputRequiredServing; + _legacyShim; + /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ + _legacyInputRequiredShim() { + return this._legacyShim ??= new LegacyInputRequiredShim({ + maxRounds: this._inputRequiredServing.maxRounds, + roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, + resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), + verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), + sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), + sendSampling: (params, options) => this.createMessage(params, options), + listRoots: (params, options) => this.listRoots(params, options) + }); + } + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). + */ + oninitialized; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._requestStateVerify = options?.requestState?.verify; + this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); + if (options?.cacheHints !== void 0) { + for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); + this._cacheHints = options.cacheHints; + } + this.setRequestHandler("initialize", (request) => this._oninitialize(request)); + this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); + if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); + if (this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Registers the built-in `logging/setLevel` request handler. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + _registerLoggingHandler() { + this.setRequestHandler("logging/setLevel", async (request, ctx) => { + const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; + const { level } = request.params; + const parseResult = parseSchema(LoggingLevelSchema, level); + if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); + return {}; + }); + } + buildContext(ctx, transportInfo) { + const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + log: (level, data, logger) => { + if (!this._capabilities.logging) return Promise.resolve(); + let threshold; + if (this._servedModernEra()) { + threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; + if (threshold === void 0) return Promise.resolve(); + } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); + if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); + return ctx.mcpReq.notify({ + method: "notifications/message", + params: { + level, + data, + logger + } + }); + }, + elicitInput: (params, options) => this.elicitInput(params, options), + requestSampling: (params, options) => this.createMessage(params, options) + }, + http: hasHttpInfo ? { + ...ctx.http, + req: transportInfo?.request, + closeSSE: transportInfo?.closeSSEStream, + closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream + } : void 0 + }; + } + _loggingLevels = /* @__PURE__ */ new Map(); + LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); + const hadLogging = !!this._capabilities.logging; + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Enforces server-side validation for `tools/call` results regardless of how the + * handler was registered, attaches the configured per-operation cache hint + * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` + * for results that do not provide their own, and owns the multi-round-trip + * seam: on the methods whose 2026-07-28 result vocabulary includes + * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an + * input-required return skips result-schema validation and is checked + * against the served era, the at-least-one rule, and the request's own + * declared client capabilities; on every other method an input-required + * return is a server bug and fails loudly. The hint rides a symbol-keyed + * property that is never serialized, so 2025-era responses are unaffected. + */ + _wrapHandler(method, handler) { + if (method !== "tools/call") { + const cacheHint = this._cacheHints?.[method]; + const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); + if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { + const result = await handler(request, ctx); + if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + }; + return async (request, ctx) => { + const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); + if (isInputRequiredResult(result)) { + if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + } + return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); + }; + } + return async (request, ctx) => { + const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + const validatedRequest = codec.validateRequest("tools/call", request); + if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); + const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); + if (isInputRequiredResult(result)) return result; + const normalizedResult = normalizeContentlessToolResult(result); + const validationResult = codec.validateResult("tools/call", normalizedResult); + if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); + return validationResult.value; + }; + } + /** + * Whether this instance is bound to a 2026-07-28-or-later protocol + * revision. Era is instance state — a serving entry (`createMcpHandler`, + * `serveStdio`) marks the instance modern at construction; a 2025-era + * `initialize` handshake binds it legacy. The multi-round-trip seam reads + * this directly: there is no per-request era consult. + */ + _servedModernEra() { + return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); + } + /** + * Invokes a handler for one of the multi-round-trip methods and applies + * the input-required seam: + * + * - a `UrlElicitationRequiredError` (or any 2025-style server→client + * request idiom) escaping the handler on a request served on the + * 2026-07-28 era fails LOUDLY with a clear steer to + * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the + * 2026-07-28 wire and the throw is not silently converted. Requests + * served on the 2025 era keep today's `-32042` behavior byte-exact (the + * error is rethrown unchanged). + * - an input-required RETURN toward a 2026-07-28 request must satisfy + * the at-least-one rule, and every embedded request must be covered by + * the capabilities declared on the request's envelope (violations + * answer the typed `-32021` error). Toward a 2025-era request the + * return is fulfilled by the default-on legacy shim, whose own gate + * consults the initialize-declared capabilities and surfaces + * violations per family; `inputRequired.legacyShim: false` restores + * the pre-shim loud failure. + */ + async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { + const servedModern = this._servedModernEra(); + const rawRequestState = ctx.mcpReq.requestState(); + if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + let ctxForHandler = ctx; + if (typeof rawRequestState === "string") { + const decoded = await this._verifyRequestState(rawRequestState, ctx, method); + if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); + } + let result; + try { + result = await handler(request, ctxForHandler); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { + if (!servedModern) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); + } + throw error; + } + if (!isInputRequiredResult(result)) return result; + if (!servedModern) { + if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); + return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); + } + const inputRequests = result.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const hasRequestState = typeof result.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + if (hasInputRequests) { + const declared = this._inputRequestCapabilityView(ctx); + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); + if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); + } + } + return result; + } + /** + * Runs the configured `requestState.verify` hook and returns its + * resolved value (`undefined` when unconfigured or the hook returns + * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; + * the reason goes to `onerror` only. + */ + async _verifyRequestState(state, ctx, method) { + if (this._requestStateVerify === void 0) return; + try { + return await this._requestStateVerify(state, ctx); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + } + } + /** + * The per-request resolved client-capabilities view: the request's own + * `_meta` envelope on the 2026 era; the `initialize`-declared state on a + * 2025-era connection. Per-request instances that never saw an + * initialize (stateless legacy) hold nothing, so gates refuse there. + */ + _inputRequestCapabilityView(ctx) { + return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; + } + /** + * Guard for the push-style server→client request APIs ({@linkcode createMessage}, + * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a + * modern-era instance: the 2026-07-28 revision has no server→client request + * channel, so the call fails before any wire traffic with a typed error + * whose message steers to `inputRequired(...)`. The base era gate would + * also reject it; this guard runs first to carry the steer. + */ + _assertPushApiInServedEra(method) { + if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { + method, + era: "2026-07-28" + }); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); + break; + case "roots/list": + if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); + break; + case "ping": break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); + break; + case "notifications/cancelled": break; + case "notifications/progress": break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "logging/setLevel": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "ping": + case "initialize": break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; + this._negotiatedProtocolVersion = protocolVersion; + this.transport?.setProtocolVersion?.(protocolVersion); + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` + * lists only modern revisions (2025-era versions are negotiated via `initialize`); + * the capabilities are advertised as-is, listChanged/subscribe bits included + * (see {@linkcode discoverAdvertisedCapabilities}). + */ + _ondiscover() { + return { + supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), + capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * The identity the 2026-era encode seam stamps into every outbound + * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR + * #3002: servers SHOULD identify themselves on every response). + */ + _outboundServerInfo() { + return this._serverInfo; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * declared capabilities, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * name and version, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientVersion() { + return this._clientVersion; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * with the client (the version the server responded with during the initialize handshake), or + * `undefined` before initialization. + * + * @deprecated Read the protocol revision from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the + * request was sent for, while on 2025-era connections this accessor keeps returning the + * `initialize`-negotiated version. The accessor remains functional — instances serving the + * 2026-07-28 era report that revision. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * Project a `tools/call` result through this instance's negotiated wire + * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on + * the 2025 era the `{result:…}` wrap when `structuredContent` is a + * non-object value or the advertised `outputSchema` had a non-object root. + * Identity for object-shaped `structuredContent` on the 2026 era. + * + * `McpServer`'s built-in `tools/call` handler routes through this method. + * Low-level `setRequestHandler('tools/call', …)` authors call it + * themselves so the projection lives in one place (the codec) and the + * server-side handler stays era-blind. + * + * This is the only codec function exposed on `Server` — the full + * `WireCodec` is intentionally not part of the public surface. + */ + projectCallToolResult(result, advertisedOutputSchema) { + return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); + } + /** + * Returns the current server capabilities. + */ + getCapabilities() { + return this._capabilities; + } + /** + * Sends a `ping` request to the connected client. + * + * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. + * If your factory serves both eras, this only works on the legacy path. + */ + async ping() { + this._assertPushApiInServedEra("ping"); + return this.request({ method: "ping" }); + } + async createMessage(params, options) { + this._assertPushApiInServedEra("sampling/createMessage"); + if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); + if (params.messages.length > 0) { + const lastMessage = params.messages.at(-1); + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); + if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + const hasTools = Boolean(params.tools || params.toolChoice); + const wide = await this.request({ + method: "sampling/createMessage", + params + }, options); + const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); + if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); + return outcome.value; + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + * + * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) + * instead. The 2025 push-style server-to-client request model is replaced by input_required + * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the + * legacy path. + */ + async elicitInput(params, options) { + this._assertPushApiInServedEra("elicitation/create"); + switch (params.mode ?? "form") { + case "url": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); + break; + case "form": + if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); + break; + } + return this._sendElicitationLeg(params, options); + } + /** + * The capability-check-free core of {@linkcode elicitInput}. The shim + * uses it because its gate differs from the public checks: a bare + * `elicitation: {}` counts as form support (the pre-mode rule), and + * accepted content passes through unvalidated for parity with the + * modern client driver (handlers validate via the schema-aware + * `acceptedContent` overload and can re-ask). + */ + async _sendElicitationLeg(params, options, behavior) { + const mode = params.mode ?? "form"; + const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; + switch (mode) { + case "url": { + const urlParams = params; + return this.request({ + method: "elicitation/create", + params: urlParams + }, options); + } + case "form": { + const formParams = params.mode === "form" ? params : { + ...params, + mode: "form" + }; + const result = await this.request({ + method: "elicitation/create", + params: formParams + }, options); + if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { + const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); + if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * The notification (and the `elicitationId` it references) exists only on protocol revision + * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the + * returned callback rejects with a typed local error before anything reaches the transport + * (the method is not part of that revision's wire registry). + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { elicitationId } + }, options); + } + /** + * Requests the list of roots from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, + * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 + * push-style server-to-client request model is replaced by input_required results in the + * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. + */ + async listRoots(params, options) { + this._assertPushApiInServedEra("roots/list"); + return this.request({ + method: "roots/list", + params + }, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ + method: "notifications/message", + params + }); + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + async sendResourceListChanged() { + return this.notification({ method: "notifications/resources/list_changed" }); + } + async sendToolListChanged() { + return this.notification({ method: "notifications/tools/list_changed" }); + } + async sendPromptListChanged() { + return this.notification({ method: "notifications/prompts/list_changed" }); + } +}; +/** +* The capability set a server advertises on `server/discover`. Pure — never +* mutates the input; the legacy `initialize` advertisement is untouched. +* +* The serving entries serve `subscriptions/listen` themselves, so the +* `listChanged` and `resources.subscribe` capability bits are advertised +* as-is: a modern-era client uses them to decide which notification types to +* request on its listen filter. +*/ +function discoverAdvertisedCapabilities(capabilities) { + return { ...capabilities }; +} + +//#endregion +//#region src/server/mcp.ts +/** +* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. +* For advanced usage (like sending notifications or setting custom request handlers), use the underlying +* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. +* +* @example +* ```ts source="./mcp.examples.ts#McpServer_basicUsage" +* const server = new McpServer({ +* name: 'my-server', +* version: '1.0.0' +* }); +* ``` +*/ +var mcp_DXXb3Vv3_McpServer = class { + /** + * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. + */ + server; + _registeredResources = {}; + _registeredResourceTemplates = {}; + _registeredTools = {}; + _registeredPrompts = {}; + /** + * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 + * registration-time scan and the pre-dispatch validation step share one + * conversion instead of paying it twice per request under the + * per-request-factory `createMcpHandler` model. + */ + _toolInputSchemaJson = {}; + /** + * The JSON-serialized `inputSchema` of a registered tool, or `undefined` + * when no such tool is registered. Used by the HTTP entry's pre-dispatch + * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema + * `tools/list` would emit, before dispatch reaches the handler). + * + * @internal + */ + toolInputSchemaJson(name) { + const tool = this._registeredTools[name]; + if (tool === void 0 || !tool.enabled) return void 0; + if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; + if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; + try { + const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + return json; + } catch { + return; + } + } + constructor(serverInfo, options) { + this.server = new Server(serverInfo, options); + if (options?.capabilities?.tools) this.setToolRequestHandlers(); + if (options?.capabilities?.resources) this.setResourceRequestHandlers(); + if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" + * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); + * const transport = new StdioServerTransport(); + * await server.connect(transport); + * ``` + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + _toolHandlersInitialized = false; + setToolRequestHandlers() { + if (this._toolHandlersInitialized) return; + this.server.assertCanSetRequestHandler("tools/list"); + this.server.assertCanSetRequestHandler("tools/call"); + this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); + this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, + annotations: tool.annotations, + icons: tool.icons, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); + return toolDefinition; + }) })); + this.server.setRequestHandler("tools/call", async (request, ctx) => { + const tool = this._registeredTools[request.params.name]; + if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + try { + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, ctx); + await this.validateToolOutput(tool, result, request.params.name); + if (isInputRequiredResult(result)) return result; + return this.server.projectCallToolResult(result, tool.outputSchemaJson); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [{ + type: "text", + text: errorMessage + }], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) return; + const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) return; + if (isInputRequiredResult(result)) return; + if (result.isError) return; + if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); + } + /** + * Executes a tool handler. + */ + async executeToolHandler(tool, args, ctx) { + return tool.executor(args, ctx); + } + _completionHandlerInitialized = false; + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) return; + this.server.assertCanSetRequestHandler("completion/complete"); + this.server.registerCapabilities({ completions: {} }); + this.server.setRequestHandler("completion/complete", async (request) => { + switch (request.params.ref.type) { + case "ref/prompt": + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case "ref/resource": + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; + const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); + if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; + const completer = getCompleter(field); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + _resourceHandlersInitialized = false; + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) return; + this.server.assertCanSetRequestHandler("resources/list"); + this.server.assertCanSetRequestHandler("resources/templates/list"); + this.server.assertCanSetRequestHandler("resources/read"); + this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); + this.server.setRequestHandler("resources/list", async (_request, ctx) => { + const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) continue; + const result = await template.resourceTemplate.listCallback(ctx); + for (const resource of result.resources) templateResources.push({ + ...template.metadata, + ...resource + }); + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler("resources/templates/list", async () => { + return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })) }; + }); + this.server.setRequestHandler("resources/read", async (request, ctx) => { + let uri; + try { + uri = new URL(request.params.uri); + } catch { + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { + uri: request.params.uri, + reason: "invalid_uri" + }); + } + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); + return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); + } + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); + } + throw new ResourceNotFoundError(request.params.uri); + }); + this._resourceHandlersInitialized = true; + } + _promptHandlersInitialized = false; + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) return; + this.server.assertCanSetRequestHandler("prompts/list"); + this.server.assertCanSetRequestHandler("prompts/get"); + this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); + this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, + icons: prompt.icons, + _meta: prompt._meta + }; + }) })); + this.server.setRequestHandler("prompts/get", async (request, ctx) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + return prompt.handler(request.params.arguments, ctx); + }); + this._promptHandlersInitialized = true; + } + registerResource(name, uriOrTemplate, config, readCallback) { + const cacheHint = config.cacheHint; + let metadata = config; + if (cacheHint !== void 0) { + assertValidCacheHint(cacheHint, `resource ${name}`); + const rest = { ...config }; + delete rest.cacheHint; + metadata = rest; + } + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: (updates) => { + if (updates.uri !== void 0 && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) this._registeredResources[updates.uri] = registeredResource; + } + if (updates.name !== void 0) registeredResource.name = updates.name; + if (updates.title !== void 0) registeredResource.title = updates.title; + if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; + if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; + if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + const variableNames = template.uriTemplate.variableNames; + if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { + let currentArgsSchema = argsSchema; + let currentCallback = callback; + const registeredPrompt = { + title, + description, + argsSchema, + icons, + _meta, + handler: createPromptHandler(name, argsSchema, callback), + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; + } + if (updates.title !== void 0) registeredPrompt.title = updates.title; + if (updates.description !== void 0) registeredPrompt.description = updates.description; + if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; + if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; + let needsHandlerRegen = false; + if (updates.argsSchema !== void 0) { + registeredPrompt.argsSchema = updates.argsSchema; + currentArgsSchema = updates.argsSchema; + needsHandlerRegen = true; + } + if (updates.callback !== void 0) { + currentCallback = updates.callback; + needsHandlerRegen = true; + } + if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); + if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + if (argsSchema) { + const shape = getSchemaShape(argsSchema); + if (shape) { + if (Object.values(shape).some((field) => { + return isCompletable(unwrapOptionalSchema(field)); + })) this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { + validateAndWarnToolName(name); + if (inputSchema !== void 0) try { + const json = standardSchemaToJsonSchema(inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); + if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); + } catch {} + let currentHandler = handler; + const registeredTool = { + title, + description, + inputSchema, + outputSchema, + outputSchemaJson: convertOutputSchemaJson(outputSchema), + annotations, + icons, + execution, + _meta, + handler, + executor: createToolExecutor(inputSchema, handler), + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + if (typeof updates.name === "string") validateAndWarnToolName(updates.name); + delete this._registeredTools[name]; + delete this._toolInputSchemaJson[name]; + if (updates.name) { + delete this._toolInputSchemaJson[updates.name]; + this._registeredTools[updates.name] = registeredTool; + name = updates.name; + } + } + if (updates.title !== void 0) registeredTool.title = updates.title; + if (updates.description !== void 0) registeredTool.description = updates.description; + let needsExecutorRegen = false; + if (updates.paramsSchema !== void 0) { + registeredTool.inputSchema = updates.paramsSchema; + delete this._toolInputSchemaJson[name]; + needsExecutorRegen = true; + } + if (updates.callback !== void 0) { + registeredTool.handler = updates.callback; + currentHandler = updates.callback; + needsExecutorRegen = true; + } + if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); + if (updates.outputSchema !== void 0) { + registeredTool.outputSchema = updates.outputSchema; + registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); + } + if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; + if (updates.icons !== void 0) registeredTool.icons = updates.icons; + if (updates._meta !== void 0) registeredTool._meta = updates._meta; + if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + registerTool(name, config, cb) { + if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); + const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; + return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); + } + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); + const { title, description, argsSchema, icons, _meta } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns `true` if the server is connected + */ + isConnected() { + return this.server.transport !== void 0; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" + * await server.sendLoggingMessage({ + * level: 'info', + * data: 'Processing complete' + * }); + * ``` + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) this.server.sendResourceListChanged(); + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) this.server.sendToolListChanged(); + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) this.server.sendPromptListChanged(); + } +}; +/** +* A resource template combines a URI pattern with optional functionality to enumerate +* all resources matching that pattern. +*/ +var ResourceTemplate = class { + _uriTemplate; + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +}; +/** +* Creates an executor that invokes the handler with the appropriate arguments. +* When `inputSchema` is defined, the handler is called with `(args, ctx)`. +* When `inputSchema` is undefined, the handler is called with just `(ctx)`. +*/ +function createToolExecutor(inputSchema, handler) { + if (inputSchema) { + const callback$1 = handler; + return async (args, ctx) => callback$1(args, ctx); + } + const callback = handler; + return async (_args, ctx) => callback(ctx); +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {} +}; +/** +* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} +* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that +* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion +* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). +*/ +function convertOutputSchemaJson(outputSchema) { + if (outputSchema === void 0) return void 0; + try { + return standardSchemaToJsonSchema(outputSchema, "output"); + } catch { + return; + } +} +/** +* Creates a type-safe prompt handler that captures the schema and callback in a closure. +* This eliminates the need for type assertions at the call site. +*/ +function createPromptHandler(name, argsSchema, callback) { + if (argsSchema) { + const typedCallback = callback; + return async (args, ctx) => { + const parseResult = await validateStandardSchema(argsSchema, args); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); + return typedCallback(parseResult.data, ctx); + }; + } else { + const typedCallback = callback; + return async (_args, ctx) => { + return typedCallback(ctx); + }; + } +} +function createCompletionResult(suggestions) { + return { completion: { + values: suggestions.map(String).slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } }; +} +const EMPTY_COMPLETION_RESULT = { completion: { + values: [], + hasMore: false +} }; +/** @internal Gets the shape of a Zod object schema */ +function getSchemaShape(schema) { + const candidate = schema; + if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; +} +/** @internal Checks if a Zod schema is optional */ +function isOptionalSchema(schema) { + return schema?.type === "optional"; +} +/** @internal Unwraps an optional Zod schema */ +function unwrapOptionalSchema(schema) { + if (!isOptionalSchema(schema)) return schema; + return schema.def?.innerType ?? schema; +} + +//#endregion + +//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map + + + + +//#region src/server/perRequestTransport.ts +/** +* The per-request micro-transport: a real, connected `Transport` whose whole +* lifetime is one HTTP exchange. See the module documentation for the +* response shapes it produces. +*/ +var PerRequestHTTPServerTransport = class { + onclose; + onerror; + onmessage; + _classification; + _responseMode; + _started = false; + _used = false; + _closed = false; + _terminalDelivered = false; + /** + * `true` only while the inbound message is being delivered synchronously + * to the connected protocol layer. The pre-handler gates (the era + * registry gate, the edge→instance handoff check, the missing-handler + * rejection) answer inside this window; request handlers always run + * after it (the protocol layer defers them to a microtask). An error + * sent inside the window is therefore ladder-originated, and an error + * sent after it is handler-produced. + */ + _dispatchWindowOpen = false; + _requestId; + _deferredResponse; + _sse; + _abortCleanup; + _keepAliveMs; + constructor(options) { + this._classification = options.classification; + this._responseMode = options.responseMode ?? "auto"; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + async start() { + if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); + this._started = true; + } + /** + * Serves the single exchange: delivers the classified message to the + * connected server instance and resolves with the HTTP response. + * + * Throws when called a second time (the transport is strictly + * single-use), or before a server has been connected to the transport. + * The returned promise rejects with a connection-closed error when the + * transport is closed before a response was produced (for example because + * the client disconnected). + */ + async handleMessage(message, extra) { + if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); + if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); + if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); + this._used = true; + const signal = extra?.request?.signal; + if (signal?.aborted) { + await this.close(); + throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); + } + const messageExtra = { + classification: this._classification, + ...extra?.request !== void 0 && { request: extra.request }, + ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } + }; + if (isJSONRPCRequest(message)) { + this._requestId = message.id; + let resolve; + let reject; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + this._deferredResponse = { + promise, + resolve, + reject, + settled: false + }; + if (signal !== void 0) { + const onAbort = () => void this.close(); + signal.addEventListener("abort", onAbort, { once: true }); + this._abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + this._dispatchWindowOpen = true; + try { + this.onmessage(message, messageExtra); + } finally { + this._dispatchWindowOpen = false; + } + if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); + return promise; + } + this.onmessage(message, messageExtra); + return new Response(null, { status: 202 }); + } + async send(message, options) { + if (this._closed) return; + const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); + const relatedId = isResponse ? message.id : options?.relatedRequestId; + if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { + if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); + return; + } + if (isResponse) { + if (this._terminalDelivered) return; + this._terminalDelivered = true; + const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; + const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; + if (ladderStatus !== void 0 && this._sse === void 0) { + this.settleResponse(Response.json(message, { + status: ladderStatus, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._sse !== void 0 || this._responseMode === "sse") { + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + this.finalizeStream(); + return; + } + this.settleResponse(Response.json(message, { + status: 200, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._responseMode === "json") return; + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + } + /** + * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the + * exchange is not currently streaming. + */ + writeCommentFrame(comment) { + if (this._closed || this._sse === void 0 || this._sse.closed) return; + const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); + this.writeFrame(`${frame}\n\n`); + } + async close() { + if (this._closed) return; + this._closed = true; + this._abortCleanup?.(); + this._abortCleanup = void 0; + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { + this._deferredResponse.settled = true; + this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); + } + this.onclose?.(); + } + settleResponse(response) { + if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; + this._deferredResponse.settled = true; + this._deferredResponse.resolve(response); + } + upgradeToSse() { + let controller; + const readable = new ReadableStream({ + start: (streamController) => { + controller = streamController; + }, + cancel: () => { + this.close(); + } + }); + this._sse = { + controller, + encoder: new TextEncoder(), + closed: false + }; + this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); + this.settleResponse(new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + })); + } + finalizeStream() { + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + queueMicrotask(() => void this.close()); + } + writeMessageFrame(message) { + this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + writeFrame(frame) { + if (this._sse === void 0 || this._sse.closed) return; + try { + this._sse.controller.enqueue(this._sse.encoder.encode(frame)); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); + } + } +}; + +//#endregion +//#region src/server/invoke.ts +/** +* Serves one classified inbound message on the given server instance and +* returns the HTTP response for the exchange. +* +* The instance is connected to a fresh single-exchange transport, the message +* is injected through the normal transport message path, and whatever the +* dispatch layer produces (the handler result, a protocol-level rejection, or +* streamed related messages followed by the result) is captured as the +* returned `Response`. For request exchanges, teardown rides the transport's +* close chain once the terminal response has been delivered; notification +* exchanges resolve with the 202 response immediately and do NOT run the +* close chain — the transport stays connected until the caller closes it or +* drops the per-request instance, which is the caller's choice either way. +*/ +async function invoke(server, message, ctx) { + const transport = new PerRequestHTTPServerTransport({ + classification: ctx.classification, + ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, + ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } + }); + await server.connect(transport); + return transport.handleMessage(message, { + ...ctx.request !== void 0 && { request: ctx.request }, + ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } + }); +} + +//#endregion +//#region src/server/streamableHttp.ts +/** +* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification +* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). +* +* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. +* +* In stateful mode: +* - Session ID is generated and included in response headers +* - Session ID is always included in initialization responses +* - Requests with invalid session IDs are rejected with `404 Not Found` +* - Non-initialization requests without a session ID are rejected with `400 Bad Request` +* - State is maintained in-memory (connections, message history) +* +* In stateless mode: +* - No Session ID is included in any responses +* - No session validation is performed +* +* @example Stateful setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: () => crypto.randomUUID() +* }); +* +* await server.connect(transport); +* ``` +* +* @example Stateless setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: undefined +* }); +* ``` +* +* @example Hono.js +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" +* app.all('/mcp', async c => { +* return transport.handleRequest(c.req.raw); +* }); +* ``` +* +* @example Cloudflare Workers +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" +* const worker = { +* async fetch(request: Request): Promise { +* return transport.handleRequest(request); +* } +* }; +* ``` +*/ +var WebStandardStreamableHTTPServerTransport = class { + sessionIdGenerator; + _started = false; + _closed = false; + _streamMapping = /* @__PURE__ */ new Map(); + _requestToStreamMapping = /* @__PURE__ */ new Map(); + _requestResponseMap = /* @__PURE__ */ new Map(); + _initialized = false; + _enableJsonResponse = false; + _standaloneSseStreamId = "_GET_stream"; + _eventStore; + _onsessioninitialized; + _onsessionclosed; + _allowedHosts; + _allowedOrigins; + _enableDnsRebindingProtection; + _retryInterval; + _supportedProtocolVersions; + _keepAliveMs; + sessionId; + onclose; + onerror; + onmessage; + constructor(options = {}) { + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + startKeepAlive(controller, encoder) { + if (this._closed) return void 0; + const timer = armSseKeepAlive(this._keepAliveMs, () => { + try { + controller.enqueue(encoder.encode(": keepalive\n\n")); + } catch { + if (timer !== void 0) clearInterval(timer); + } + }); + return timer; + } + /** + * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) throw new Error("Transport already started"); + this._started = true; + } + /** + * Sets the supported protocol versions for header validation. + * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. + */ + setSupportedProtocolVersions(versions) { + this._supportedProtocolVersions = versions; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { + code, + message + }; + if (options?.data !== void 0) error.data = options.data; + return Response.json({ + jsonrpc: "2.0", + error, + id: null + }, { + status, + headers: { + "Content-Type": "application/json", + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, `undefined` if validation passes. + */ + validateRequestHeaders(req) { + if (!this._enableDnsRebindingProtection) return; + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get("host"); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get("origin"); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + } + /** + * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` + * Returns a `Response` object (Web Standard) + */ + async handleRequest(req, options) { + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const validationError = this.validateRequestHeaders(req); + if (validationError) return validationError; + switch (req.method) { + case "POST": return this.handlePostRequest(req, options); + case "GET": return this.handleGetRequest(req); + case "DELETE": return this.handleDeleteRequest(req); + default: return this.handleUnsupportedRequest(); + } + } + /** + * Returns true if the client's protocol version supports empty SSE data in + * priming events (the fix shipped with protocol version `2025-11-25`). + * + * The version is checked for membership in this transport instance's + * supported protocol versions rather than with an open-ended + * `>= '2025-11-25'` comparison: the value may come from an `initialize` + * request body, which (unlike the `MCP-Protocol-Version` header) is not + * validated against `supportedProtocolVersions` before reaching this + * check. An unknown future version string must not silently enable + * behavior reserved for versions this transport actually supports. + */ + supportsEmptySSEData(protocolVersion) { + return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if `eventStore` is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (a supported + * version that is >= `2025-11-25`). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) return; + if (!this.supportsEmptySSEData(protocolVersion)) return; + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles `GET` requests for SSE stream + */ + async handleGetRequest(req) { + if (!req.headers.get("accept")?.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); + } + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + if (this._eventStore) { + const lastEventId = req.headers.get("last-event-id"); + if (lastEventId) return this.replayEvents(lastEventId); + } + if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); + } + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } catch {} + } + }); + keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); + return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); + } + try { + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); + return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); + } + if (this._streamMapping.get(streamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); + } + } + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + let cancelled = false; + let replayedStreamId; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + cancelled = true; + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); + } + }); + const replayedEventIds = /* @__PURE__ */ new Set(); + replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { + replayedEventIds.add(eventId); + if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { + streamController.close(); + } catch {} + } }); + if (this._closed || cancelled) { + try { + streamController.close(); + } catch {} + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + this._streamMapping.get(replayedStreamId)?.cleanup(); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + replayedEventIds, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + }); + if (replayedStreamId !== this._standaloneSseStreamId) { + if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + } + if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + if (eventId) eventData += `id: ${eventId}\n`; + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } catch (error) { + this.onerror?.(error); + return false; + } + } + /** + * Handles unsupported requests (`PUT`, `PATCH`, etc.) + */ + handleUnsupportedRequest() { + this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: "Method not allowed." + }, + id: null + }, { + status: 405, + headers: { + Allow: "GET, POST, DELETE", + "Content-Type": "application/json" + } + }); + } + /** + * Handles `POST` requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + const acceptHeader = req.headers.get("accept"); + if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); + } + if (!isJsonContentType(req.headers.get("content-type"))) { + this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const request = req; + let rawMessage; + if (options?.parsedBody === void 0) try { + rawMessage = await req.json(); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); + } + else rawMessage = options.parsedBody; + let messages; + try { + messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); + if (isInitializationRequest) { + if (this._initialized && this.sessionId !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); + } + if (messages.length > 1) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + if (!isInitializationRequest) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + if (!messages.some((element) => isJSONRPCRequest(element))) { + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + return new Response(null, { status: 202 }); + } + const streamId = crypto.randomUUID(); + const initRequest = messages.find((m) => isInitializeRequest(m)); + const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (this._enableJsonResponse) return new Promise((resolve) => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + }); + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + for (const message of messages) if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(streamId); + try { + streamController.close(); + } catch {} + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + for (const message of messages) { + let closeSSEStream; + let closeStandaloneSSEStream; + if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { + authInfo: options?.authInfo, + request, + closeSSEStream, + closeStandaloneSSEStream + }); + } + if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { + status: 200, + headers + }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); + } + } + /** + * Handles `DELETE` requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + try { + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + return new Response(null, { status: 200 }); + } finally { + await this.close(); + } + } + /** + * Validates session ID for non-initialization requests. + * Returns `Response` error if invalid, `undefined` otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === void 0) return; + if (!this._initialized) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); + } + const sessionId = req.headers.get("mcp-session-id"); + if (!sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); + } + if (sessionId !== this.sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Session not found")); + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + } + /** + * Validates the `MCP-Protocol-Version` header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with `MCP-Protocol-Version` header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the `MCP-Protocol-Version` header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get("mcp-protocol-version"); + if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { + const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(400, -32e3, error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + for (const { cleanup } of this._streamMapping.values()) cleanup(); + this._streamMapping.clear(); + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) return; + const stream = this._streamMapping.get(streamId); + if (stream) stream.cleanup(); + } + /** + * Close the standalone `GET` SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) stream.cleanup(); + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; + if (requestId === void 0) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); + let eventId; + if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === void 0) return; + if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + return; + } + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); + let stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse) { + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + stream = this._streamMapping.get(streamId); + } + if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); + if (relatedIds.every((id) => this._requestResponseMap.has(id))) { + if (!stream) { + if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + if (this._enableJsonResponse && stream.resolveJson) { + const headers = { "Content-Type": "application/json" }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); + if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { + status: 200, + headers + })); + else stream.resolveJson(Response.json(responses, { + status: 200, + headers + })); + stream.cleanup(); + } else stream.cleanup(); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +}; + +//#endregion +//#region src/server/createMcpHandler.ts +/** +* The JSON-RPC id to echo on an entry-built error response: the body's `id` +* when the body is a single JSON-RPC request whose id is a string or number, +* `null` otherwise. Error responses must carry the id of the request they +* correspond to whenever it could be read; `null` is reserved for the cases +* where no single request id is determinable — unparseable bodies, body-less +* methods, notifications, posted responses and batch arrays. +*/ +function echoableRequestId(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) return null; + const { method, id } = body; + if (typeof method !== "string") return null; + return typeof id === "string" || typeof id === "number" ? id : null; +} +function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message, + ...data !== void 0 && { data } + }, + id + }, { status: httpStatus }); +} +function rejectionResponse(rejection, id = null) { + return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); +} +function toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} +function internalServerErrorResponse(id = null) { + return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); +} +/** +* The entry's default legacy serving (`legacy: 'stateless'`): per-request +* stateless serving of 2025-era traffic using the same factory as the modern +* path. Exported as a standalone building block for hand-wired compositions +* (for example mounting legacy stateless serving on its own route next to a +* strict modern endpoint). +* +* Each POST is served by a fresh instance from the factory connected to a +* fresh streamable HTTP transport constructed with only +* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. +* Because serving is per-request and stateless, GET and DELETE (2025 session +* operations) are answered with `405` / `Method not allowed.`, exactly like the +* canonical stateless example. +* +* The optional `onerror` callback receives factory and serving failures on +* this leg (reporting only — the response stays the 500 internal-error body). +* The entry passes its own `onerror` here when expanding the default, so +* legacy-leg failures are never silently swallowed. +*/ +function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { + return async (request, options) => { + if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); + try { + const product = await factory({ + era: "legacy", + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + requestInfo: request + }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: void 0, + ...keepAliveMs !== void 0 && { keepAliveMs } + }); + await product.connect(transport); + const teardown = () => { + transport.close().catch(() => {}); + product.close().catch(() => {}); + }; + request.signal?.addEventListener("abort", teardown, { once: true }); + const response = await transport.handleRequest(request, { + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } + }); + if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { + teardown(); + return response; + } + const reader = response.body.getReader(); + let toreDown = false; + const completeExchange = () => { + if (!toreDown) { + toreDown = true; + teardown(); + } + }; + const monitoredBody = new ReadableStream({ + pull: async (controller) => { + try { + const { done, value } = await reader.read(); + if (done) { + completeExchange(); + controller.close(); + return; + } + if (value !== void 0) controller.enqueue(value); + } catch (error) { + completeExchange(); + controller.error(error); + } + }, + cancel: (reason) => { + completeExchange(); + return reader.cancel(reason).catch(() => {}); + } + }); + return new Response(monitoredBody, { + status: response.status, + statusText: response.statusText, + headers: response.headers + }); + } catch (error) { + try { + onerror?.(toError(error)); + } catch {} + return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); + } + }; +} +function legacyStatelessFallback(factory, onerror) { + return createLegacyStatelessFallback(factory, onerror); +} +/** +* The entry's classification step: read the request body exactly once (unless +* a pre-parsed body is supplied) and classify the request with +* {@linkcode classifyInboundRequest}. This is the single code path behind both +* {@linkcode createMcpHandler}'s routing and the exported +* {@linkcode isLegacyRequest} predicate, so the two can never disagree. +* +* Pass `needsForward: false` when the caller never reads `forwardRequest` — +* the body-preserving clone is then skipped and `forwardRequest` is the +* (consumed) input request. +*/ +async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { + const httpMethod = request.method.toUpperCase(); + let body; + let parsedBody = providedParsedBody; + let forwardRequest = request; + let unparseable = false; + if (httpMethod === "POST") { + if (parsedBody === void 0) { + if (needsForward) forwardRequest = request.clone(); + let bodyText; + try { + bodyText = await request.text(); + } catch { + return { step: "unreadable-body" }; + } + try { + body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); + } catch { + unparseable = true; + } + if (!unparseable && body !== void 0) parsedBody = body; + } else body = parsedBody; + if (unparseable || body === void 0) return { + step: "no-json-body", + forwardRequest + }; + } + return { + step: "classified", + outcome: classifyInboundRequest({ + httpMethod, + protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0, + ...body !== void 0 && { body } + }), + body, + parsedBody, + forwardRequest + }; +} +/** +* Whether {@linkcode createMcpHandler} would route this request to its legacy +* (2025-era) serving rather than the modern (2026-07-28) path. +* +* Call it with just the request: `await isLegacyRequest(request)`. For a +* `POST` the body is read from an internal clone, so the request you pass +* stays fully readable for whichever handler you route it to — no second +* argument is needed. (In a Node `(req, res)` handler, build that `Request` +* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body +* parser, which has already drained the Node stream, build it as +* `toWebRequest(req, req.body)` so the bytes come from the parsed body — +* either way the predicate still takes just the request.) The optional +* `parsedBody` is a perf escape hatch for a body you already hold parsed: +* pass it and the predicate classifies from the value directly, reading and +* cloning nothing. It is needed, not just faster, when the request's own +* body was already read — the internal clone is then impossible (cloning a +* used body throws a `TypeError`), so such a single-argument call rejects +* instead of guessing. +* +* This is the entry's own classification step exported as a predicate — it +* runs exactly the code `createMcpHandler` runs to make the routing decision, +* not a re-implementation — so a hand-wired composition that branches on it +* can never disagree with the entry. It is classification only: hand-wired +* compositions must validate Content-Type themselves (415 for POSTs whose +* media type is not `application/json`, via {@linkcode isJsonContentType}) +* before dispatching either leg — routing the legacy leg into the SDK +* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy +* deployment (for example a sessionful streamable HTTP wiring) serving 2025 +* traffic next to a strict modern endpoint, now that the entry has no +* handler-valued `legacy` option: +* +* ```ts +* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; +* +* const modern = createMcpHandler(factory, { legacy: 'reject' }); +* +* export default { +* async fetch(request: Request): Promise { +* if (await isLegacyRequest(request)) { +* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring +* return myExistingLegacyHandler(request); +* } +* return modern.fetch(request); +* } +* }; +* ``` +* +* Semantics (identical to the entry's routing): +* +* - Returns `true` only for requests with no per-request `_meta` envelope +* claim: claim-less POSTs (including the `initialize` handshake and 2025-era +* notification POSTs without a modern protocol-version header), body-less +* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted +* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. +* - Returns `false` for everything the modern path answers, including its +* validation-ladder rejections: a request carrying the envelope claim (even +* one naming a revision the endpoint does not serve — the modern path +* answers it with the unsupported-protocol-version error), a malformed +* envelope behind a present claim (answered `-32602`), a request whose +* `MCP-Protocol-Version` header names a modern revision but that lacks the +* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers +* routing on the predicate must send `false` traffic to the modern handler, +* never to a legacy handler — the modern path owns those error answers. +* - `server/discover` probes sent by negotiating clients always carry the +* envelope claim, so they are never legacy; a hand-built claim-less POST to +* a method named `server/discover` has no claim and classifies legacy, +* exactly as the entry itself routes it. +*/ +async function isLegacyRequest(request, parsedBody) { + const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); + return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; +} +/** +* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a +* per-request server factory and, by default, falls back to old-school +* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a +* modern-only strict endpoint. +* +* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, +* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap +* the handler once with `toNodeHandler(handler)` from +* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, +* put Origin/Host validation in front of the handler — the entry itself is +* deliberately validation-free: +* +* ```ts +* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; +* +* export default { +* async fetch(request: Request): Promise { +* const rejected = +* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? +* originValidationResponse(request, localhostAllowedOrigins()); +* return rejected ?? handler.fetch(request); +* } +* }; +* ``` +* +* Use ONE factory for both legs: the same tools/resources/prompts definition +* backs the modern path and the stateless legacy fallback, so the two eras can +* never drift apart. To keep an existing legacy deployment (for example a +* sessionful streamable HTTP wiring) serving 2025 traffic instead of the +* stateless fallback, route in user land with {@linkcode isLegacyRequest} in +* front of a strict handler — see that predicate's documentation for the +* pattern. Power users composing transport-neutral routing can also use the +* exported building blocks directly: {@linkcode classifyInboundRequest} for +* the era decision and `PerRequestHTTPServerTransport` for single-exchange +* serving — such compositions must reject POSTs whose Content-Type media type +* is not `application/json` (415) before parsing the body, using +* {@linkcode isJsonContentType}; neither building block performs this +* validation itself. +* +* The entry performs no token verification: `authInfo` given to `fetch` is +* passed through to handlers and the factory as-is and is never derived from +* request headers. +*/ +function createMcpHandler(factory, options = {}) { + const { legacy, onerror, responseMode } = options; + if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); + /** Modern per-request instances with an exchange still in flight (close() tears these down). */ + const inflight = /* @__PURE__ */ new Set(); + let closed = false; + const reportError = (error) => { + try { + onerror?.(error); + } catch {} + }; + const bus = options.bus ?? new InMemoryServerEventBus(reportError); + const notify = createServerNotifier(bus); + const listenRouter = createListenRouter({ + bus, + maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, + keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, + onerror: reportError + }); + if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); + const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); + async function serveModern(route, request, authInfo) { + const claimedRevision = route.classification.revision; + if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedRevision ?? "unknown" + }); + reportError(error); + return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); + } + const stdHeaderRejection = validateStandardRequestHeaders({ + httpMethod: request.method, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0 + }, route); + if (stdHeaderRejection !== void 0) { + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); + return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); + } + const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; + const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; + if (route.messageKind === "request") { + const required = requiredClientCapabilitiesForRequest(route.message.method); + if (required !== void 0) { + const missing = missingClientCapabilities(required, declaredClientCapabilities); + if (missing !== void 0) { + const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); + reportError(error); + return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); + } + } + } + const product = await factory({ + era: "modern", + ...authInfo !== void 0 && { authInfo }, + requestInfo: request + }); + const server = product instanceof McpServer ? product.server : product; + if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { + const capabilities = server.getCapabilities(); + const serverInfo = serverIdentityOf(server); + product.close().catch(reportError); + return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); + } + if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { + const callParams = route.message.params; + const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; + const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); + if (inputSchema !== void 0) { + const scan = scanXMcpHeaderDeclarations(inputSchema); + if (scan.valid && scan.declarations.length > 0) { + const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); + if (rejection !== void 0) { + product.close().catch(reportError); + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); + return rejectionResponse(rejection, route.message.id); + } + } + } + } + setNegotiatedProtocolVersion(server, claimedRevision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (meta !== void 0) seedClientIdentityFromEnvelope(server, { + clientInfo: meta[CLIENT_INFO_META_KEY], + clientCapabilities: declaredClientCapabilities + }); + const previousOnClose = server.onclose; + inflight.add(server); + server.onclose = () => { + inflight.delete(server); + previousOnClose?.(); + }; + try { + const response = await invoke(product, route.message, { + classification: route.classification, + request, + ...authInfo !== void 0 && { authInfo }, + ...responseMode !== void 0 && { responseMode }, + ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } + }); + if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); + return response; + } catch (error) { + if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); + await server.close().catch(() => {}); + inflight.delete(server); + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(route.message)); + } + } + async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { + if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { + ...authInfo !== void 0 && { authInfo }, + ...parsedBody !== void 0 && { parsedBody } + }); + const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (strict === void 0) return new Response(null, { status: 202 }); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); + return rejectionResponse(strict, echoableRequestId(parsedBody)); + } + async function handle(request, requestOptions) { + const authInfo = requestOptions?.authInfo; + if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { + reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); + if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); + if (classified.step === "no-json-body") { + if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); + return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); + } + const { outcome, body, parsedBody, forwardRequest } = classified; + try { + switch (outcome.kind) { + case "reject": + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); + return rejectionResponse(outcome, echoableRequestId(body)); + case "modern": return await serveModern(outcome, request, authInfo); + case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); + } + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(body)); + } + } + const fetchFace = async (request, requestOptions) => { + if (closed) throw new Error("This MCP handler has been closed"); + try { + return await handle(request, requestOptions); + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); + } + }; + return { + fetch: fetchFace, + notify, + bus, + close: async () => { + closed = true; + listenRouter.closeAll(); + const closing = [...inflight].map((server) => server.close().catch(() => {})); + inflight.clear(); + await Promise.all(closing); + } + }; +} + +//#endregion +//#region src/server/middleware/bearerAuth.ts +function headerQuotedValue(value) { + return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); +} +function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { + let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; + if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; + if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; + return header; +} +/** +* Validate a raw `Authorization` header value as a Bearer token and return +* the verified {@link AuthInfo}. +* +* The runtime-neutral core of Bearer authentication: it parses the header, +* runs the verifier, enforces `requiredScopes`, and rejects tokens without an +* expiration or past it. On any failure it throws an {@link OAuthError} — +* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP +* answer, or use {@link requireBearerAuth} to get both steps as one call. +* +* Framework adapters build on this: `requireBearerAuth` from +* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. +*/ +async function verifyBearerToken(authorizationHeader, options) { + const { verifier, requiredScopes = [] } = options; + if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); + const [type, token] = authorizationHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); + const authInfo = await verifier.verifyAccessToken(token); + if (requiredScopes.length > 0) { + if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); + } + if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); + else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); + return authInfo; +} +/** +* Build the HTTP answer for a Bearer authentication failure. +* +* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and +* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` +* challenge, with `resource_metadata` when configured so clients can discover +* the Authorization Server), `500` for `server_error`, `400` for anything +* else. A non-`OAuthError` value answers `500 server_error`. The body is the +* OAuth error JSON. +*/ +function bearerAuthChallengeResponse(error, options) { + const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; + if (!(error instanceof OAuthError)) { + const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); + return Response.json(serverError.toResponseObject(), { status: 500 }); + } + switch (error.code) { + case OAuthErrorCode.InvalidToken: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 401, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.InsufficientScope: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 403, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); + default: return Response.json(error.toResponseObject(), { status: 400 }); + } +} +/** +* Require a valid Bearer token on web-standard requests. +* +* The framework-free counterpart of `requireBearerAuth` from +* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a +* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The +* returned gate resolves to the verified {@link AuthInfo}, or to the +* ready-to-return challenge `Response` when the request must be refused. +* +* @example +* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" +* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); +* +* async function fetchHandler(request: Request): Promise { +* const auth: AuthInfo | Response = await gate(request); +* if (auth instanceof Response) return auth; +* return handler.fetch(request, { authInfo: auth }); +* } +* ``` +*/ +function requireBearerAuth(options) { + const { verifier, requiredScopes = [], resourceMetadataUrl } = options; + const resolved = { + verifier, + requiredScopes, + resourceMetadataUrl + }; + return async (request) => { + const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); + try { + return await verifyBearerToken(authorizationHeader || void 0, resolved); + } catch (error) { + return bearerAuthChallengeResponse(error, resolved); + } + }; +} + +//#endregion +//#region src/server/middleware/hostHeaderValidation.ts +/** +* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). +* +* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). +* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). +*/ +function validateHostHeader(hostHeader, allowedHostnames) { + if (!hostHeader) return { + ok: false, + errorCode: "missing_host", + message: "Missing Host header" + }; + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_host_header", + message: `Invalid Host header: ${hostHeader}`, + hostHeader + }; + } + if (!allowedHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_host", + message: `Invalid Host: ${hostname}`, + hostHeader, + hostname + }; + return { + ok: true, + hostname + }; +} +/** +* Convenience allowlist for `localhost` DNS rebinding protection. +*/ +function localhostAllowedHostnames() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for DNS rebinding protection. +* @example +* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" +* const result = validateHostHeader(req.headers.get('host'), ['localhost']); +* ``` +*/ +function hostHeaderValidationResponse(req, allowedHostnames) { + const result = validateHostHeader(req.headers.get("host"), allowedHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/middleware/oauthMetadata.ts +function checkIssuerUrl(issuer, allowInsecure) { + if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); + if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); +} +/** +* Derive the RFC 9728 Protected Resource Metadata document from +* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL +* (HTTPS required outside localhost) in the process. +* +* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build +* on this; use it directly when serving the document through your own +* routing — or call it once at startup to fail fast on a misconfigured +* issuer before any request arrives. +*/ +function buildOAuthProtectedResourceMetadata(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); + return { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; +} +/** +* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server +* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. +* +* @example +* ```ts +* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) +* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' +* ``` +*/ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; +} +/** The RFC 9728 path-aware well-known path for a resource URL. */ +function protectedResourceMetadataPath(resourceServerUrl) { + const rsPath = stripTrailingSlash(resourceServerUrl.pathname); + return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; +} +function stripTrailingSlash(path) { + return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; +} +const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; +function metadataDocumentResponse(request, metadata) { + if (request.method === "OPTIONS") { + const requestedHeaders = request.headers.get("access-control-request-headers"); + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": ALLOWED_METHODS, + ...requestedHeaders === null ? {} : { + "Access-Control-Allow-Headers": requestedHeaders, + Vary: "Access-Control-Request-Headers" + } + } + }); + } + if (request.method !== "GET" && request.method !== "HEAD") { + const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); + return Response.json(error.toResponseObject(), { + status: 405, + headers: { + Allow: ALLOWED_METHODS, + "Access-Control-Allow-Origin": "*" + } + }); + } + const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); + return request.method === "HEAD" ? new Response(null, { + status: response.status, + headers: response.headers + }) : response; +} +/** +* Serve the two OAuth discovery documents an MCP server acting as a Resource +* Server exposes, from a web-standard `fetch(request)` handler: +* +* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected +* Resource Metadata, derived from the supplied options (path-aware: the +* resource URL's path is reflected in the route). +* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization +* Server Metadata, passed through verbatim. +* +* Returns the matched document `Response` (JSON with permissive CORS, `405` +* with an `Allow` header for non-GET methods, `204` for CORS preflight), or +* `undefined` when the request path is neither well-known route — fall +* through to your own routing. The framework-free counterpart of +* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with +* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so +* unauthenticated clients can discover the AS from the `401` challenge. +* +* @example +* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" +* async function fetchHandler(request: Request): Promise { +* return oauthMetadataResponse(request, options) ?? serveMcp(request); +* } +* ``` +*/ +function oauthMetadataResponse(request, options) { + const requestPath = stripTrailingSlash(new URL(request.url).pathname); + if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); + if (requestPath === "/.well-known/oauth-authorization-server") { + buildOAuthProtectedResourceMetadata(options); + return metadataDocumentResponse(request, options.oauthMetadata); + } +} + +//#endregion +//#region src/server/middleware/originValidation.ts +/** +* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). +* +* - A missing/empty `Origin` header passes: non-browser clients do not send one, +* and only browser-originated requests carry the header this check defends against. +* - Allowlist items are hostnames only (no scheme, no port), the same convention as +* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). +* - Any present value that cannot be parsed as an origin URL — including the literal +* `null` origin browsers send for opaque contexts — is rejected (deny on failure). +*/ +function validateOriginHeader(originHeader, allowedOriginHostnames) { + if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; + let hostname; + try { + hostname = new URL(originHeader).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + } + if (hostname === "") return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + if (!allowedOriginHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_origin", + message: `Invalid Origin: ${hostname}`, + originHeader, + hostname + }; + return { + ok: true, + origin: originHeader, + hostname + }; +} +/** +* Convenience allowlist of localhost-class origin hostnames, mirroring +* `localhostAllowedHostnames`. +*/ +function localhostAllowedOrigins() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC +* error response when the request's `Origin` header is not allowed, and +* `undefined` when the request may proceed. +* +* ```ts +* const rejected = originValidationResponse(request, localhostAllowedOrigins()); +* if (rejected) return rejected; +* ``` +*/ +function originValidationResponse(req, allowedOriginHostnames) { + const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/requestStateCodec.ts +const PREFIX = "v1."; +function bytesToBase64Url(bytes) { + let bin = ""; + for (const b of bytes) bin += String.fromCodePoint(b); + return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} +function constantTimeTagEqual(a, b) { + if (a.length !== b.length) return false; + let r = 0; + for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); + return r === 0; +} +function base64UrlToBytes(s) { + const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return bytes; +} +/** +* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` +* (protocol revision 2026-07-28). +* +* `requestState` round-trips through the client and is attacker-controlled +* input on re-entry. The SDK applies no protection of its own; this helper is +* the convenience implementation of the spec's integrity MUST so authors don't +* hand-roll HMAC. Wire shape: +* +* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) +* +* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` +* — the binding value is never embedded raw. +* +* The codec is **signed, not encrypted**: the body is integrity-protected but +* the client can base64url-decode it and read the payload (`p`) in clear. Do +* not put secrets in the payload; use an AEAD construction if confidentiality +* is required. The handler reads its payload back via the typed +* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` +* (integrity proven, payload decoded) by the time the handler is entered. +* +* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for +* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). +* See `examples/mrtr/server.ts` for a worked end-to-end example. +* +* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference +* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and +* derives independent cipher / bind-HMAC sub-keys from the operator secret via +* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is +* supplied. This codec deliberately ships only the signed mode and a single +* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and +* an encrypted mode are intentionally out of scope for the initial release. +*/ +function createRequestStateCodec(options) { + const subtle = globalThis.crypto?.subtle; + if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); + const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); + if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); + const ttlSeconds = options.ttlSeconds ?? 600; + if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); + const bind = options.bind; + let cryptoKey; + const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { + name: "HMAC", + hash: "SHA-256" + }, false, ["sign", "verify"]); + const utf8 = new TextEncoder(); + const BIND_LABEL = "mcp.requestState.bind:"; + const bindTag = async (value) => { + return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); + }; + return { + async mint(payload, ctx) { + const envelope = { + p: payload, + exp: Math.floor(Date.now() / 1e3) + ttlSeconds + }; + if (bind !== void 0) { + if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); + envelope.b = await bindTag(bind(ctx)); + } + const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); + return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; + }, + async verify(state, ctx) { + const dot = state.lastIndexOf("."); + if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); + const body = state.slice(3, dot); + let macBytes; + try { + macBytes = base64UrlToBytes(state.slice(dot + 1)); + } catch { + throw new Error("malformed"); + } + if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); + let envelope; + try { + envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); + } catch { + throw new Error("malformed"); + } + if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); + if (bind !== void 0) { + const expected = await bindTag(bind(ctx)); + if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); + } else if (envelope.b !== void 0) throw new Error("bind"); + return envelope.p; + } + }; +} + +//#endregion +//#region src/fromJsonSchema.ts +let _defaultValidator; +function dist_fromJsonSchema(schema, validator) { + return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); +} + +//#endregion + +//# sourceMappingURL=index.mjs.map +const mcpApps = Object.freeze([]); + +/* export default */ const mcp_status_073c1634_0 = (mcpApps); + +// Generated by agent-bundle. Do not edit. +const meta_name = "mcp-app-example"; +const packageName = "@agent-bundle-example/mcp-app"; +const packageVersion = undefined; +const meta_version = "1.0.0"; +const meta_meta = Object.freeze({ + name: meta_name, + packageName: packageName, + packageVersion: packageVersion, + version: meta_version +}); +/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + + + + +const app = mcp_status_073c1634_0["0"]; +if (app === undefined) throw new Error('Expected the status MCP App.'); +const serviceCatalog = Object.freeze({ + compiler: healthyCompilerStatus, + 'payments-api': Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'P95 latency', + status: 'failing' + }) + ]), + service: 'payments-api', + status: 'degraded', + summary: 'Payment latency is above the release threshold.' + }) +}); +const createStatusServer = ()=>{ + // The compiler stamps this project's identity into `agent-bundle/meta`, so + // the wire identity cannot drift from the config or package.json. + const server = new mcp_DXXb3Vv3_McpServer({ + name: meta_name, + version: (/* inlined export .version */"1.0.0") + }); + server.registerResource(app.name, app.resourceUri, { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + mimeType: app.mimeType + }, async (uri)=>({ + contents: [ + { + mimeType: app.mimeType, + text: app.html, + uri: uri.href + } + ] + })); + server.registerTool('show-status', { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + description: 'Show the health of one example service.', + inputSchema: schemas_object({ + service: schemas_enum([ + 'compiler', + 'payments-api' + ]) + }) + }, async ({ service })=>{ + const result = serviceCatalog[service]; + return { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + content: [ + { + text: result.summary, + type: 'text' + } + ], + structuredContent: result + }; + }); + return server; +}; +/** + * Default-exported server factory: `agent-bundle build` detects it and wraps + * this entry in the framework stdio lifecycle shell (console-to-stderr guard, + * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). + */ /* export default */ const mcp_status = (createStatusServer); + + + + + +//#region src/server/stdio.ts +/** +* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. +* +* This transport is only available in Node.js environments. +* +* @example +* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* const transport = new StdioServerTransport(); +* await server.connect(transport); +* ``` +*/ +var stdio_StdioServerTransport = class { + _readBuffer; + _started = false; + _closed = false; + constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); + } + onclose; + onerror; + onmessage; + _ondata = (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error) { + this.onerror?.(error); + this.close().catch(() => {}); + } + }; + _onerror = (error) => { + this.onerror?.(error); + }; + _onstdouterror = (error) => { + this.onerror?.(error); + this.close().catch(() => {}); + }; + /** + * Starts listening for messages on `stdin`. + */ + async start() { + if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + this._stdout.on("error", this._onstdouterror); + } + processReadBuffer() { + while (true) try { + const message = this._readBuffer.readMessage(); + if (message === null) break; + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + this._stdout.off("error", this._onstdouterror); + if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); + return new Promise((resolve, reject) => { + const json = serializeMessage(message); + let settled = false; + const onError = (error) => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + reject(error); + }; + const onDrain = () => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + resolve(); + }; + this._stdout.once("error", onError); + if (this._stdout.write(json)) { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + resolve(); + } else if (!settled) this._stdout.once("drain", onDrain); + }); + } +}; + +//#endregion +//#region src/server/serveStdio.ts +/** +* How long the probe-discard path waits for the probe instance to answer the +* requests it was delivered before closing it. The wait normally settles as +* soon as the DiscoverResult is handed to the wire (or immediately, when a +* delivered cancellation already settled the probe); the bound is a backstop +* so no edge can ever hold the connection's inbound pump indefinitely behind +* the discard. +*/ +const DISCARD_ANSWER_TIMEOUT_MS = 3e3; +/** +* The transport a pinned instance is connected to: a thin channel that writes +* through to the entry-owned wire transport and receives the messages the +* entry forwards. The wire transport itself is never handed to an instance — +* that is what lets the entry discard an optimistic probe instance (close the +* channel) without tearing down the connection. +*/ +var StdioConnectionChannel = class { + onclose; + onerror; + onmessage; + _closed = false; + /** Request ids the entry delivered to the instance that the instance has not yet answered. */ + _pendingRequests = /* @__PURE__ */ new Set(); + _drainWaiters = []; + constructor(_wire, _onInstanceClose, _outboundIntercept) { + this._wire = _wire; + this._onInstanceClose = _onInstanceClose; + this._outboundIntercept = _outboundIntercept; + } + async start() {} + async send(message, options) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + const { id } = message; + if (id !== void 0) this._settle(id); + } + if (this._closed) return; + if (this._outboundIntercept?.(message) === "handled") return; + return this._wire.send(message, options); + } + setProtocolVersion = (version) => { + this._wire.setProtocolVersion?.(version); + }; + /** Forwards one inbound message to the connected instance. */ + deliver(message, extra) { + if (this._closed) return; + if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); + else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0) this._settle(cancelledId); + } + this.onmessage?.(message, extra); + } + /** + * Resolves once every request delivered to the instance has been answered + * through {@linkcode send}, settled by a delivered cancellation, or the + * channel has been closed and nothing further can be answered. The wait is + * bounded by `timeoutMs` as a backstop so no edge can hold the caller + * indefinitely; resolves `false` only when the bound elapsed with requests + * still unanswered. Used by the probe-discard path so a probe request the + * entry accepted is never silently dropped. + */ + async whenRequestsAnswered(timeoutMs) { + if (this._closed || this._pendingRequests.size === 0) return true; + return await new Promise((resolve) => { + const waiter = () => { + clearTimeout(timer); + resolve(true); + }; + const timer = setTimeout(() => { + this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); + resolve(false); + }, timeoutMs); + this._drainWaiters.push(waiter); + }); + } + async close() { + if (this._closed) return; + this._closed = true; + this._pendingRequests.clear(); + this._releaseDrainWaiters(); + try { + this._onInstanceClose(); + } finally { + this.onclose?.(); + } + } + _settle(id) { + this._pendingRequests.delete(id); + if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); + } + _releaseDrainWaiters() { + const waiters = this._drainWaiters; + this._drainWaiters = []; + for (const waiter of waiters) waiter(); + } +}; +/** +* Classifies one message of the opening exchange with the same body-primary +* rules the HTTP entry applies per request: `initialize` is the legacy +* handshake unless it carries a valid modern envelope claim; a present claim +* is validated (never silently ignored); a claim-less message is 2025-era +* traffic. There is no header layer on stdio, so the body is the only signal. +*/ +function classifyOpeningMessage(message) { + const params = message.params; + if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { + const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (!hasEnvelopeClaim(params)) return { + kind: "legacy", + reason: "no-claim" + }; + const meta = requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return { + kind: "invalid-envelope", + issue: firstIssue + }; + const claimedVersion = envelopeClaimVersion(params); + if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { + kind: "unsupported-revision", + requested: claimedVersion ?? "unknown" + }; + return { + kind: "modern", + revision: claimedVersion, + classification: { + era: "modern", + revision: claimedVersion + } + }; +} +/** +* Serves MCP over stdio from a server factory, owning the era decision for +* the connection: the opening exchange selects the era, ONE instance from the +* factory is pinned for the connection lifetime, and everything after passes +* straight through to it. See the module documentation for the opening rules. +* +* ```ts +* import { serveStdio } from '@modelcontextprotocol/server/stdio'; +* +* serveStdio(() => { +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); +* // register tools/resources/prompts once — the same factory serves both eras +* return server; +* }); +* ``` +*/ +function serveStdio(factory, options = {}) { + const legacyMode = options.legacy ?? "serve"; + const wire = options.transport ?? new stdio_StdioServerTransport(); + let state = { phase: "opening" }; + /** Channel currently being discarded (its close must not tear the connection down). */ + let discarding; + let closing = false; + /** + * Whether the connection has been torn down (`handle.close()` or the wire + * closing). The opening arms re-check this after every await: a close can + * race factory construction, and the continuation must neither resurrect + * the connection state nor keep a late-resolved instance around. + */ + const isTornDown = () => closing || state.phase === "closed"; + const reportError = (error) => { + try { + options.onerror?.(error); + } catch {} + }; + const writeErrorResponse = (id, code, message, data) => wire.send({ + jsonrpc: "2.0", + id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }).catch((error) => reportError(stdio_toError(error))); + /** + * Entry-handled `subscriptions/listen` for this connection: holds the + * active subscriptions, serves inbound listen / cancelled-of-listen + * before the pinned instance is consulted, and rewrites the instance's + * outbound change notifications onto the active subscriptions. Only + * consulted on a modern-pinned connection — on a legacy connection + * change notifications pass straight through (the 2025 unsolicited + * delivery model is unchanged). + */ + const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); + /** Outbound intercept installed on a modern instance's channel. */ + const modernOutboundIntercept = (message) => { + if (!isJSONRPCNotification(message)) return void 0; + const routed = listenRouter.routeOutbound(message); + if (routed === "passthrough") return void 0; + for (const stamped of routed) wire.send({ + jsonrpc: "2.0", + ...stamped + }).catch((error) => reportError(stdio_toError(error))); + return "handled"; + }; + /** + * Entry-handled inbound listen routing for a modern-pinned connection. + * Returns `true` when the message was served at the entry and must NOT + * be delivered to the pinned instance. + */ + const tryServeListen = async (message) => { + if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { + const meta = requestMetaOf(message.params); + const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { + key: "_meta", + problem: "the per-request envelope is required on protocol revision 2026-07-28" + }; + const claimedVersion = envelopeClaimVersion(message.params); + let reply; + if (issue !== void 0) reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` + } + }; + else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedVersion ?? "unknown" + }); + reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: error.code, + message: error.message, + data: error.data + } + }; + } else reply = listenRouter.serve(message); + await wire.send("error" in reply ? reply : { + jsonrpc: "2.0", + method: reply.method, + params: reply.params + }).catch((error) => reportError(stdio_toError(error))); + return true; + } + if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; + } + return false; + }; + /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ + const answerLegacyRejection = (request, reason, requestedVersion) => { + const rejection = modernOnlyStrictRejection({ + kind: "legacy", + reason, + ...requestedVersion !== void 0 && { requestedVersion } + }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (rejection === void 0) return Promise.resolve(); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); + return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); + }; + const onInstanceClosed = (channel) => { + if (closing || channel === discarding) return; + closeAll(); + }; + const connectInstance = async (era, revision) => { + const product = await factory({ era }); + const server = product instanceof McpServer ? product.server : product; + if (era === "modern") { + setNegotiatedProtocolVersion(server, revision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); + } + const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); + await product.connect(channel); + return { + product, + channel + }; + }; + /** Closes an instance whose factory resolved only after the connection was torn down. */ + const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); + const discardProbeInstance = async (instance) => { + discarding = instance.channel; + try { + if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); + await instance.product.close(); + } catch (error) { + reportError(stdio_toError(error)); + } finally { + discarding = void 0; + } + }; + const processMessage = async (message) => { + if (state.phase === "closed") return; + if (state.phase === "pinned") { + if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { + await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); + return; + } + if (state.era === "modern" && await tryServeListen(message)) return; + state.instance.channel.deliver(message); + return; + } + if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { + reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); + return; + } + const opening = classifyOpeningMessage(message); + switch (opening.kind) { + case "invalid-envelope": { + const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); + else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); + return; + } + case "unsupported-revision": + if (isJSONRPCRequest(message)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: opening.requested + }); + reportError(error); + await writeErrorResponse(message.id, error.code, error.message, error.data); + } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); + return; + case "modern": + if (isJSONRPCRequest(message) && message.method === "server/discover") { + if (state.phase === "probe") { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "probe", + instance + }; + instance.channel.deliver(message, { classification: opening.classification }); + return; + } + if (state.phase === "probe") { + if (isJSONRPCNotification(message)) { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + state = { + phase: "pinned", + era: "modern", + instance: state.instance + }; + } else { + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "modern", + instance + }; + } + if (await tryServeListen(message)) return; + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + case "legacy": { + if (legacyMode === "reject") { + if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); + return; + } + if (state.phase === "probe") { + await discardProbeInstance(state.instance); + if (isTornDown()) return; + state = { phase: "opening" }; + } + const instance = await connectInstance("legacy"); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "legacy", + instance + }; + state.instance.channel.deliver(message); + return; + } + } + }; + const queue = []; + let pumping = false; + const pump = async () => { + if (pumping) return; + pumping = true; + try { + while (queue.length > 0) { + const message = queue.shift(); + try { + await processMessage(message); + } catch (error) { + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); + reportError(stdio_toError(error)); + } + } + } finally { + pumping = false; + } + }; + const closeAll = async () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); + if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + await wire.close().catch((error) => reportError(stdio_toError(error))); + }; + wire.onmessage = (message) => { + queue.push(message); + pump(); + }; + wire.onerror = (error) => { + reportError(error); + if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); + }; + wire.onclose = () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + }; + const started = wire.start().catch((error) => { + reportError(stdio_toError(error)); + throw error; + }); + started.catch(() => {}); + return { close: async () => { + await started.catch(() => {}); + await closeAll(); + } }; +} +function stdio_toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} + +//#endregion + +//# sourceMappingURL=stdio.mjs.map +const defaultHeartbeatIntervalMs = 300000; +const defaultActivityThrottleMs = 60000; +const defaultShutdownTimeoutMs = 5000; +const defaultHeartbeatName = 'agent-bundle'; +const redirectConsoleToStderr = ()=>{ + const originalStdoutWrite = process.stdout.write.bind(process.stdout); + const stderrConsole = new console.Console({ + stderr: process.stderr, + stdout: process.stderr + }); + const methods = [ + 'debug', + 'dir', + 'error', + 'info', + 'log', + 'trace', + 'warn' + ]; + for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); + process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); + return Object.freeze({ + restoreProtocolStdout: ()=>{ + process.stdout.write = originalStdoutWrite; + } + }); +}; +const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ + const startedAt = Date.now(); + let lastActivityAt = startedAt; + let lastActivityLogAt = 0; + const log = (reason)=>{ + const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); + const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); + writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); + }; + const timer = setInterval(()=>log('interval'), intervalMs); + timer.unref?.(); + return Object.freeze({ + log, + noteActivity: ()=>{ + lastActivityAt = Date.now(); + if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { + lastActivityLogAt = lastActivityAt; + log('activity'); + } + }, + stop: ()=>clearInterval(timer) + }); +}; +const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ + const heartbeat = createHeartbeat({ + ...void 0 === activityThrottleMs ? {} : { + activityThrottleMs + }, + ...void 0 === heartbeatIntervalMs ? {} : { + intervalMs: heartbeatIntervalMs + }, + ...void 0 === serverName ? {} : { + name: serverName + }, + writeLine: heartbeatEnabled ? writeLine : ()=>void 0 + }); + const keepalive = setInterval(()=>void 0, 60000); + keepalive.unref?.(); + let shuttingDown = false; + const shutdown = async (exitCode = 0)=>{ + if (shuttingDown) return; + shuttingDown = true; + signals.off('SIGINT', handleSigint); + signals.off('SIGTERM', handleSigterm); + stdin.off?.('end', handleStdinEnd); + clearInterval(keepalive); + heartbeat.stop(); + await Promise.race([ + Promise.allSettled([ + Promise.resolve().then(()=>transport.close()), + Promise.resolve().then(()=>server.close()) + ]), + new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) + ]); + exit(exitCode); + }; + const handleSigint = ()=>{ + shutdown(130); + }; + const handleSigterm = ()=>{ + shutdown(143); + }; + const handleStdinEnd = ()=>{ + shutdown(0); + }; + signals.on('SIGINT', handleSigint); + signals.on('SIGTERM', handleSigterm); + stdin.once?.('end', handleStdinEnd); + transport.onclose = ()=>{ + shutdown(0); + }; + await server.connect(transport); + const originalOnMessage = transport.onmessage; + transport.onmessage = (message, extra)=>{ + heartbeat.noteActivity(); + originalOnMessage?.(message, extra); + }; + return Object.freeze({ + heartbeat, + shutdown + }); +}; +const runGeneratedStdioMcpEntry = async (options)=>{ + const guard = redirectConsoleToStderr(); + const entry = await options.loadEntry(); + const factory = entry.default; + if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); + const server = await factory(); + const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); + guard.restoreProtocolStdout(); + const transport = new StdioServerTransport(); + return runStdioServer({ + ...options.lifecycle, + server, + serverName: options.serverName, + transport: transport + }); +}; + + + +await runGeneratedStdioMcpEntry({ + loadEntry: ()=>Promise.resolve(status_namespaceObject), + serverName: "status" +}); + +export {}; diff --git a/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs new file mode 100644 index 000000000..a6f274bf6 --- /dev/null +++ b/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs @@ -0,0 +1,60 @@ +import { readFile } from "node:fs/promises"; + + + + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + +const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); +/** + * `agent-bundle build` detects the `main` export and generates the process + * envelope (argv, awaiting, numeric-return exit-code adoption) around it. + */ const main = async ()=>{ + try { + const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); + if (!isHealthyCompilerFixture(fixture)) { + throw new Error('compiler fixture must contain the exact healthy compiler status'); + } + process.stdout.write('Compiler fixture is healthy.\n'); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const check_service_fixture_entry_main = main; +if (typeof check_service_fixture_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/mcp-app/src/scripts/check-service-fixture.ts"); +} +const code = await check_service_fixture_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md new file mode 100644 index 000000000..8f91a79d7 --- /dev/null +++ b/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md @@ -0,0 +1,33 @@ +--- +name: service-readiness +description: Reviews service health evidence and records an auditable readiness decision. +--- +# Service readiness + +## When to use + +Use this Skill when a release, incident decision, or service handoff needs a +clear health verdict backed by named checks and current evidence. + +## Required resources + +- Apply [the service status policy](references/status-policy.md) before + classifying a healthy, degraded, or blocked result. +- Deliver the decision with [the readiness report](assets/readiness-report.md). + +## Workflow + +1. Identify the service and collect its current summary and every labelled + check. Record the command, time, result, and evidence source. +2. Classify any failing check with the status policy. A degraded service is not + release-ready until its failing check has an approved mitigation. +3. State the readiness verdict only after confirming availability and the + service-specific release threshold. +4. Complete the report with the status, checks, evidence, owner, and next + action. Do not omit a failing check from the final decision. + +## Final report requirements + +State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the +service summary; list each labelled check and its status; identify the owner +and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md new file mode 100644 index 000000000..3da5d52ea --- /dev/null +++ b/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md @@ -0,0 +1,22 @@ +# Service readiness report + +## Verdict + +State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. + +## Evidence + +Record the collection time, command or artifact, service summary, and source. + +## Checks + +List every labelled check with its observed status and release threshold. + +## Findings and mitigation + +For each non-passing check, record the impact, owner, mitigation, due date, +and the evidence required to clear it. + +## Next action + +Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md new file mode 100644 index 000000000..7e5766172 --- /dev/null +++ b/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md @@ -0,0 +1,22 @@ +# Service status policy + +## Evidence standard + +Readiness evidence must identify the service, collection time, check label, +observed status, and source command or artifact. Missing or stale evidence is +not a passing check. + +## Status classification + +- **Healthy**: every required release check is passing. +- **Degraded**: availability remains sufficient, but a release threshold such + as P95 latency is failing. Record an owner and mitigation before release. +- **Blocked**: availability or a critical safety check is failing. Do not + release until new passing evidence is collected. +- **Needs evidence**: the service or any required check cannot be verified. + +## Release decision + +Issue `ready` only for a healthy service with current evidence. A degraded +service needs an explicit mitigation decision; a blocked service cannot pass; +and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/portable/INSTALL.md b/examples/mcp-app/artifact/portable/INSTALL.md new file mode 100644 index 000000000..5ba00d88e --- /dev/null +++ b/examples/mcp-app/artifact/portable/INSTALL.md @@ -0,0 +1,19 @@ +# Install mcp-app-example + +A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Portable Agent Plugin + +Portable is a distribution profile, not a host runtime with one universal install location. +This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). +Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run +`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT +are also native clients. The bundled installer provides the Cursor local copy: + +```sh +node ./install.mjs +``` diff --git a/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json new file mode 100644 index 000000000..a765aa4b5 --- /dev/null +++ b/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json @@ -0,0 +1,9 @@ +{ + "service": "compiler", + "status": "healthy", + "summary": "Compiler service is ready for release.", + "checks": [ + { "label": "Availability", "status": "passing" }, + { "label": "Build queue", "status": "passing" } + ] +} diff --git a/examples/mcp-app/artifact/portable/install.mjs b/examples/mcp-app/artifact/portable/install.mjs new file mode 100644 index 000000000..1d942a81a --- /dev/null +++ b/examples/mcp-app/artifact/portable/install.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto'; +import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const pluginName = "mcp-app-example"; +const pluginVersion = "1.0.0"; +const source = resolve(fileURLToPath(new URL('.', import.meta.url))); +const cursorRoot = join(homedir(), '.cursor'); +const installRoot = join(cursorRoot, 'plugins', 'local'); +const destination = join(installRoot, pluginName); + +const exists = async (path) => { + try { await lstat(path); return true; } + catch (error) { if (error?.code === 'ENOENT') return false; throw error; } +}; + +const treeHash = async (root, prefix = '') => { + const rootMetadata = await lstat(root); + if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { + throw new Error('Refusing unsupported filesystem entry ".".'); + } + const hash = createHash('sha256'); + const visit = async (relative) => { + const absolute = join(root, relative); + const metadata = await lstat(absolute); + if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { + throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); + } + if (metadata.isDirectory()) { + for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); + return; + } + hash.update(relative.replaceAll('\\', '/')); + hash.update('\0'); + hash.update(await readFile(absolute)); + hash.update('\0'); + }; + for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); + return hash.digest('hex'); +}; + +const installedVersion = async () => { + for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { + try { + const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); + if (typeof value.version === 'string') return value.version; + } catch (error) { if (error?.code !== 'ENOENT') throw error; } + } + return undefined; +}; + +if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { + throw new Error(`Cursor is not installed in ${cursorRoot}.`); +} +await mkdir(installRoot, { recursive: true }); +if (await exists(destination)) { + const currentVersion = await installedVersion(); + if (currentVersion !== undefined && currentVersion !== pluginVersion) { + throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); + } + if (source === destination || await treeHash(source) === await treeHash(destination)) { + console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); + process.exit(0); + } + throw new Error(`Refusing content collision at ${destination}.`); +} + +const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); +const stage = join(stageParent, 'bundle'); +try { + await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); + await treeHash(stage); + await rename(stage, destination); + console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); +} finally { + await rm(stageParent, { force: true, recursive: true }); +} diff --git a/examples/mcp-app/artifact/portable/mcp-apps/status.html b/examples/mcp-app/artifact/portable/mcp-apps/status.html new file mode 100644 index 000000000..d1ca000c0 --- /dev/null +++ b/examples/mcp-app/artifact/portable/mcp-apps/status.html @@ -0,0 +1,154 @@ + + + + + + Service status + + + +
+
MCP App example
+

No service selected

+
unknown
+

Invoke the readiness tool to inspect a service.

+
    + + + + +

    +
    + + diff --git a/examples/mcp-app/artifact/portable/mcp.json b/examples/mcp-app/artifact/portable/mcp.json new file mode 100644 index 000000000..ac9282f22 --- /dev/null +++ b/examples/mcp-app/artifact/portable/mcp.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json","mcpServers":{"status":{"args":["mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"${PLUGIN_ROOT}","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs new file mode 100644 index 000000000..6b4d8ca65 --- /dev/null +++ b/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs @@ -0,0 +1,30768 @@ +import node_process from "node:process"; + +// The require scope +var __webpack_require__ = {}; + +// webpack/runtime/define_property_getters +(() => { +__webpack_require__.d = (exports, getters, values) => { + var define = (defs, kind) => { + for(var key in defs) { + if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { + Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); + } + } + }; + define(getters, "get"); + define(values, "value"); +}; +})(); +// webpack/runtime/has_own_property +(() => { +__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +})(); +// webpack/runtime/make_namespace_object +(() => { +// define __esModule on exports +__webpack_require__.r = (exports) => { + if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { + Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); + } + Object.defineProperty(exports, '__esModule', { value: true }); +}; +})(); + +// NAMESPACE OBJECT: ./src/mcp/status.ts +var status_namespaceObject = {}; +__webpack_require__.r(status_namespaceObject); +__webpack_require__.d(status_namespaceObject, { + createStatusServer: () => (createStatusServer), + "default": () => (mcp_status) }); + + +// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs +var stdio_namespaceObject = {}; +__webpack_require__.r(stdio_namespaceObject); +__webpack_require__.d(stdio_namespaceObject, { + StdioServerTransport: () => (stdio_StdioServerTransport) }); + + +//#region rolldown:runtime +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); +var __exportAll = (all, symbols) => { + let target = {}; + for (var name in all) { + __defProp(target, name, { + get: all[name], + enumerable: true + }); + } + if (symbols) { + __defProp(target, Symbol.toStringTag, { value: "Module" }); + } + return target; +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { + key = keys[i]; + if (!__hasOwnProp.call(to, key) && key !== except) { + __defProp(to, key, { + get: ((k) => from[k]).bind(null, key), + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable + }); + } + } + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { + value: mod, + enumerable: true +}) : target, mod)); + +//#endregion + +//#region ../core-internal/src/validators/dialects.ts +/** +* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). +*/ +const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); +const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); +const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); +const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); +/** +* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with +* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so +* wire-layer callers can consult it for documents whose dialect may be unsupported. +*/ +function declares2019Dialect($schema) { + return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); +} +/** +* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means +* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the +* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling +* provider's escape hatch in that message. +*/ +function declaredDialect(schema, remedy) { + if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; + const declared = schema.$schema.replace(/#$/, ""); + if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; + if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; + if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; + throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); +} + +//#endregion + +//# sourceMappingURL=dialects-DoSzNhcb.mjs.map + +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function toZod() { + return (schema) => schema; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function util_cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const ratio = val / step; + const roundedRatio = Math.round(ratio); + // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. + const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); + if (Math.abs(ratio - roundedRatio) < tolerance) + return 0; + return ratio - roundedRatio; +} +const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function util_esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function util_isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const util_allowsEval = /* @__PURE__*/ util_cached(() => { + // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. + if (globalConfig.jitless) { + return false; + } + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (util_isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (util_isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + if (o instanceof Map) + return new Map(o); + if (o instanceof Set) + return new Set(o); + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); +const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ + "string", + "number", + "bigint", + "boolean", + "symbol", + "undefined", +]))); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; + }); +} +// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. +const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}))(); +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".pick() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + // `for...in` skips symbols, so a symbol in the mask would select nothing + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + assignProp(newShape, key, currDef.shape[key]); + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(".omit() cannot be used on object schemas containing refinements"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values + const existingShape = schema._zod.def.shape; + for (const key of Reflect.ownKeys(shape)) { + if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { + throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); + } + } + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + }); + return clone(schema, def); +} +function merge(a, b) { + if (!b?._zod?.def) { + throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); + } + if (a._zod.def.checks?.length) { + throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); + } + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: b._zod.def.checks ?? [], + }); + return clone(a, def); +} +function partial(Class, schema, mask, name = "partial") { + const currDef = schema._zod.def; + const checks = currDef.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error(`.${name}() cannot be used on object schemas containing refinements`); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + else { + // the spread copies symbol keys; `for...in` would not reach them + for (const key of Reflect.ownKeys(oldShape)) { + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +function util_required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key of Reflect.ownKeys(mask)) { + if (!Object.prototype.hasOwnProperty.call(shape, key)) { + throw new Error(`Unrecognized key: "${String(key)}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key of Reflect.ownKeys(oldShape)) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + }); + return clone(schema, def); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. +function explicitlyAborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue === false) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ +function attachSchema(issues, start, inst) { + var _a; + for (let i = start; i < issues.length; i++) { + (_a = issues[i]).schema ?? (_a.schema = inst); + } +} +function finalizeIssue(iss, ctx, config) { + var _a; + // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. + const traits = iss.inst?._zod?.traits; + if (traits?.has("$ZodType")) { + if (traits.has("$ZodCheck")) + (_a = iss).schema ?? (_a.schema = iss.inst); + else + iss.schema = iss.inst; + } + // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. + const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; + const message = iss.message + ? iss.message + : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(schemaError?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"); + const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; + rest.path ?? (rest.path = []); + rest.message = message; + if (ctx?.reportInput) { + rest.input = _input; + } + return rest; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +const highSurrogate = /[\uD800-\uDBFF]/; +// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. +function codePointLength(str) { + const units = str.length; + if (!highSurrogate.test(str)) + return units; + let count = units; + for (let i = 0; i < units - 1; i++) { + if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { + count--; + i++; + } + } + return count; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function parsedType(data) { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "nan" : "number"; + } + case "object": { + if (data === null) { + return "null"; + } + if (Array.isArray(data)) { + return "array"; + } + const obj = data; + if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { + return obj.constructor.name; + } + } + } + return t; +} +function util_issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class util_Class { + constructor(..._args) { } +} +////////// PROTOTYPE INSTALLERS ////////// +// +// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. +/** + * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. + * + * Call this from a `proto` initializer, which runs once per prototype — never per instance. + */ +function util_members(proto, table) { + for (const key in table) { + const desc = Object.getOwnPropertyDescriptor(table, key); + // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was + if (desc.get) + Object.defineProperty(proto, key, { ...desc, enumerable: false }); + // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` + else + defineBound(proto, key, desc.value); + } +} +/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ +function util_own(inst, key, value, enumerable = true) { + Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); + return value; +} +/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ +function hide(inst, key, value) { + return util_own(inst, key, value, false); +} +function defineBound(proto, key, fn) { + Object.defineProperty(proto, key, { + configurable: true, + get() { + // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method + return this == null ? fn : util_own(this, key, fn.bind(this)); + }, + set(value) { + util_own(this, key, value); + }, + }); +} +/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ +function claim(inst, sentinel) { + const proto = Object.getPrototypeOf(inst); + // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. + return sentinel in proto ? undefined : proto; +} +// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. +let installing; +// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. +let broke = false; +const breaker = { + configurable: true, + get() { + broke = true; + return undefined; + }, +}; +/** + * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s + * constructor, computed from the internals object itself and cached there on + * first read. One accessor per constructor rather than one per instance. + */ +function defineLazyInternal(inst, key, compute) { + const proto = Object.getPrototypeOf(inst._zod); + if (key in proto && installing !== inst._zod) { + // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. + installing = undefined; + return; + } + installing = inst._zod; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. + Object.defineProperty(this, key, breaker); + const outer = broke; + broke = false; + try { + const value = compute(this); + // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. + if (broke) + delete this[key]; + else + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + broke = broke || outer; + return value; + } + catch (err) { + // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. + delete this[key]; + broke = broke || outer; + throw err; + } + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, value }); + }, + }); +} +/** + * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own + * data property. One accessor per constructor rather than one per instance, because an own accessor + * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. + */ +function installLazyProp(inst, key, make, enumerable) { + const proto = claim(inst, key); + if (!proto) + return; + Object.defineProperty(proto, key, { + configurable: true, + get() { + // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. + const desc = { configurable: true, writable: true, enumerable, value: undefined }; + Object.defineProperty(this, key, desc); + // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches + desc.value = make(this); + Object.defineProperty(this, key, desc); + return desc.value; + }, + set(value) { + Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); + }, + }); +} +/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ +const CONSTANT_CATCH = "~constantCatch"; +/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ +function constantCatch(value) { + const fn = () => value; + fn[CONSTANT_CATCH] = true; + return fn; +} + +var core_a; + +/** A special constant with type `never` */ +const NEVER = /*@__PURE__*/ Object.freeze({ + status: "aborted", +}); +/* Shared descriptor for installing `_zod`; defineProperty reads it + * synchronously, so reusing one object avoids a per-instance allocation. */ +const _zodDesc = { value: undefined, enumerable: false }; +// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error +let _E = "captureStackTrace" in Error ? Error : null; +// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot +function newError(Definition) { + const E = _E; + if (E) { + const saved = E.stackTraceLimit; + if (typeof saved === "number") { + try { + E.stackTraceLimit = 0; + } + catch { + _E = null; + return new Definition(); + } + try { + return new Definition(); + } + finally { + E.stackTraceLimit = saved; + } + } + } + return new Definition(); +} +function $constructor(name, initializer, +/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ +proto, params) { + // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. + const zodProto = {}; + // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. + function Internals(def) { + this.def = def; + this.constr = _; + this.traits = new Set(); + } + Internals.prototype = zodProto; + const protoMembers = proto; + // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. + const initialized = protoMembers && new WeakSet(); + function init(inst, def) { + if (!inst._zod) { + _zodDesc.value = new Internals(def); + try { + Object.defineProperty(inst, "_zod", _zodDesc); + } + finally { + // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. + _zodDesc.value = undefined; + } + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + if (initialized) { + // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. + const own = Object.getPrototypeOf(inst); + const ctorProto = inst._zod.constr.prototype; + let up = own; + while (up && up !== ctorProto) + up = Object.getPrototypeOf(up); + const target = up ?? own; + if (!initialized.has(target)) { + initialized.add(target); + util_members(target, protoMembers); + } + } + // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype + const proto = _.prototype; + for (const k in proto) { + if (!Object.prototype.hasOwnProperty.call(proto, k)) + continue; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + const inst = params?.Parent ? newError(Definition) : this; + init(inst, def); + const deferred = inst._zod.deferred; + if (deferred) { + for (const fn of deferred) { + fn(); + } + // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. + inst._zod.deferred = undefined; + } + // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. + const pp = globalThis.__zod_globalConfig?.postProcessor; + if (pp) + pp(inst); + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); +const globalConfig = globalThis.__zod_globalConfig; +function core_config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +class $ZodCyclicError extends Error { + constructor() { + super(`Cannot parse a reference cycle that closes through a transform`); + this.name = "ZodCyclicError"; + } +} +/** Keyed off the context object every schema in one parse call already shares. */ +const STATE = "~memo"; +const NO_ISSUES = []; +// Receivers prefix paths in place, so the cache and every hand-out need their own copies. +function cloneIssues(issues) { + return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); +} +const recursive = /*@__PURE__*/ new WeakMap(); +/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ +function isRecursive(inst, stack) { + const cached = recursive.get(inst); + if (cached !== undefined) + return cached; + // Relative to the walk in progress, so not cached. + if (stack.has(inst)) + return true; + stack.add(inst); + let result = false; + const check = (child) => { + if (!result && child?._zod && isRecursive(child, stack)) + result = true; + }; + const def = inst._zod.def; + const kind = def.type; + switch (kind) { + case "object": { + // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen + for (const key of Reflect.ownKeys(def.shape)) + check(def.shape[key]); + check(def.catchall); + break; + } + case "array": + check(def.element); + break; + case "tuple": + for (const el of def.items) + check(el); + check(def.rest); + break; + case "record": + case "map": + check(def.keyType); + check(def.valueType); + break; + case "set": + check(def.valueType); + break; + case "union": + for (const el of def.options) + check(el); + break; + case "intersection": + check(def.left); + check(def.right); + break; + case "optional": + case "nullable": + case "default": + case "prefault": + case "catch": + case "readonly": + case "nonoptional": + case "promise": + case "success": + check(def.innerType); + break; + case "pipe": + check(def.in); + check(def.out); + break; + case "function": + check(def.input); + check(def.output); + break; + // reading `_zod.innerType` resolves the getter once and caches it + case "lazy": + check(inst._zod.innerType); + break; + // a leaf by choice: `parts` are regex fragments, not data positions + case "template_literal": + // leaves + case "string": + case "number": + case "int": + case "boolean": + case "bigint": + case "symbol": + case "undefined": + case "null": + case "void": + case "never": + case "any": + case "unknown": + case "date": + case "nan": + case "enum": + case "literal": + case "file": + case "transform": + case "custom": + break; + default: { + // a new built-in kind becomes a compile error here + kind; + // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code + for (const key in def) { + const desc = Object.getOwnPropertyDescriptor(def, key); + if (!desc || desc.get) + continue; + const value = desc.value; + if (!value || typeof value !== "object") + continue; + if (value._zod) + check(value); + else if (Array.isArray(value)) + for (const el of value) + check(el); + } + } + } + stack.delete(inst); + recursive.set(inst, result); + return result; +} +/** + * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. + * Exported for `z.compile`, which refuses to compile such a schema: cycle + * breaking is driven from here off state keyed on the parse context, and a + * generated fast path has no context to key on. + */ +function isRecursiveSchema(inst) { + return isRecursive(inst, new Set()); +} +function bucketFor(state, inst) { + let bucket = state.buckets.get(inst); + if (!bucket) { + bucket = new Map(); + state.buckets.set(inst, bucket); + } + return bucket; +} +// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. +let handoff; +// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. +const memoizer_open = []; +const memoizer_memo = { + alloc(_inst, payload, empty) { + const bucket = handoff; + if (!bucket) + return empty; + handoff = undefined; + const entry = { value: empty, issues: null }; + bucket.set(payload.value, entry); + memoizer_open.push(entry); + return empty; + }, + guard(inst) { + var _a; + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. + if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) + throw new $ZodCyclicError(); + return base(payload, ctx); + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, + attach(inst) { + var _a; + let isRecursiveInst; + // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes + let lastCtx; + let lastBucket; + // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred.push(() => { + const base = inst._zod.parse; + const wrapped = (payload, ctx) => { + if (isRecursiveInst === undefined) { + isRecursiveInst = isRecursive(inst, new Set()); + if (!isRecursiveInst) { + // Nothing here can ever fire, so take it back out. + inst._zod.parse = base; + if (inst._zod.run === wrapped) + inst._zod.run = base; + return base(payload, ctx); + } + } + const input = payload.value; + if (input === null || typeof input !== "object") + return base(payload, ctx); + let state = ctx[STATE]; + if (!state) { + state = { buckets: new Map(), backEdges: undefined }; + ctx[STATE] = state; + } + let bucket; + if (lastCtx === ctx) { + bucket = lastBucket; + } + else { + bucket = bucketFor(state, inst); + lastCtx = ctx; + lastBucket = bucket; + } + const hit = bucket.get(input); + if (hit) { + payload.value = hit.value; + if (hit.issues) { + if (hit.issues.length) + payload.issues.push(...cloneIssues(hit.issues)); + } + else { + // Still being parsed: its own checks cover it, so skip them here. + payload.memo = true; + state.backEdges ?? (state.backEdges = new Set()); + state.backEdges.add(hit.value); + } + return payload; + } + handoff = bucket; + const depth = memoizer_open.length; + const result = base(payload, ctx); + handoff = undefined; + // A container that rejected its input outright allocated nothing. + const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; + // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. + if (result instanceof Promise) { + return result.then((r) => { + if (entry) + entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; + return r; + }); + } + if (entry) + entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; + return result; + }; + inst._zod.parse = wrapped; + if (inst._zod.run === base) + inst._zod.run = wrapped; + }); + }, +}; +/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ +function memoizer() { + return memoizer_memo; +} +/** Whether this value is a node a back-edge resolved to before it finished. */ +function isBackEdge(ctx, value) { + const backEdges = ctx[STATE]?.backEdges; + return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); +} + + +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const cuid = /^[cC][0-9a-z]{6,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +function nanoidOfLength(length) { + return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); +} +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?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)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); +const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); +const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. +const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const regexes_ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/; +const mac = (delimiter) => { + const escapedDelim = util.escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const regexes_base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; +const httpProtocol = /^https?$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 +const e164 = /^\+[1-9]\d{6,14}$/; +// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). +const creditCard = /^\d(?:[ -]?\d){11,18}$/; +const dateSource = `(?:(?:\\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])))`; +/** Anchors a pattern source. The interpolation lives here rather than at the call site because + * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it + * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ +function regexes_anchor(source) { + return new RegExp(`^${source}$`); +} +const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : args.seconds + ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function regexes_time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const opts = ["Z"]; + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them + const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; + const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const regexes_string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?$/; +const regexes_boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const regexes_hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); +const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); +const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); +const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); +const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); +const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); + +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ +const _whenHasSize = (payload) => { + const val = payload.value; + return !util.nullish(val) && val.size !== undefined; +}; +/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ +const _whenHasLength = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; +}; +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_big", + maximum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin: numericOriginMap[typeof payload.value] ?? origin, + code: "too_small", + minimum: typeof def.value === "object" ? def.value.getTime() : def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN + def.value !== BigInt(0) && payload.value % def.value === BigInt(0) + : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + inclusive: true, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + }; +}))); +const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: util.getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: util.getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. + const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. + const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 + ? codePointLength(input) + : units; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const units = input.length; + // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. + const length = typeof input === "string" && units >= def.length && units <= def.length * 2 + ? codePointLength(input) + : units; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + // `String.prototype.includes(sub, position)` matches `sub` at `position` + // OR LATER, so the pattern must allow at least `position` leading chars + // (`{N,}`), not exactly `position` chars (`{N}`). + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...util.prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}))); +const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +class Doc { + constructor(args = [], closed = {}) { + this.content = []; + this.indent = 0; + this.args = args; + this.closed = closed; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const content = this?.content ?? [``]; + const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); + return factory(...Object.values(this.closed)); + } +} + + + +/* Computing the message eagerly is expensive (pretty-printed JSON of all + * issues), so defer it until first read. The accessor functions and + * descriptors are shared across instances to keep error construction + * cheap; the computed message is cached on the internals object. The + * setter preserves plain assignment semantics for consumers that + * overwrite `message`. */ +function _getMessage() { + const internals = this._zod; + internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); + return internals.message; +} +function _setMessage(value) { + this._zod.message = value; +} +const _messageDesc = { + get: _getMessage, + set: _setMessage, + enumerable: true, + configurable: true, +}; +const errors_zodDesc = { value: undefined, enumerable: false }; +const _issuesDesc = { value: undefined, enumerable: false }; +/* Prototypes that already carry the lazy `toString`. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +const errors_initializer = (inst, def) => { + inst.name = "$ZodError"; + errors_zodDesc.value = inst._zod; + Object.defineProperty(inst, "_zod", errors_zodDesc); + _issuesDesc.value = def; + Object.defineProperty(inst, "issues", _issuesDesc); + // Clear the shared slots; a retained `value` pins the last error's issues. + errors_zodDesc.value = undefined; + _issuesDesc.value = undefined; + Object.defineProperty(inst, "message", _messageDesc); + /* `toString` lives as a non-enumerable lazy getter on the shared + * prototype; on first access it caches a per-instance closure so + * detached usage still works. */ + const proto = Object.getPrototypeOf(inst); + if (!_installedToString.has(proto)) { + _installedToString.add(proto); + Object.defineProperty(proto, "toString", { + configurable: true, + enumerable: false, + get() { + const value = () => this.message; + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); + }, + }); + } +}; +const $ZodError = $constructor("$ZodError", errors_initializer); +const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { + Parent: Error, +}); +/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member + * ("toString", "constructor") would otherwise read through to the prototype, and assigning + * "__proto__" would hit the setter instead of creating a key. */ +function errors_node(obj, key, make) { + if (!Object.prototype.hasOwnProperty.call(obj, key)) { + if (key === "__proto__") { + Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); + } + else { + obj[key] = make(); + } + } + return obj[key]; +} +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error, path = []) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. + if (el === "_errors") { + if (terminal) + curr._errors.push(mapper(issue)); + i++; + continue; + } + // A path element may collide with an inherited property name such as + // "__proto__" or "constructor". Truthiness checks read the prototype + // (so no node is created, then ._errors.push throws), and bracket + // assignment of "__proto__" hits the setter instead of creating an + // own key. Guard the read with hasOwnProperty and create the node + // with defineProperty so any path element becomes a real own key. + if (!Object.prototype.hasOwnProperty.call(curr, el)) { + Object.defineProperty(curr, el, { + value: { _errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + const node = curr[el]; + if (terminal) { + node._errors.push(mapper(issue)); + } + curr = node; + i++; + } + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, [...path, ...issue.path]); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + // el may collide with an inherited property name ("__proto__", + // "constructor", ...); ??= reads the prototype so the node is never + // created and curr.errors.push throws. Guard with hasOwnProperty and + // create the node with defineProperty so "__proto__" becomes a real + // own key rather than invoking the prototype setter. + if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { + Object.defineProperty(curr.properties, el, { + value: { errors: [] }, + enumerable: true, + writable: true, + configurable: true, + }); + } + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + + + + +// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. +function finalizeParams(callee, params) { + return { callee: params?.callee ?? callee, Err: params?.Err }; +} +const parse_parse = (_Err) => { + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, _params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); +const parse_parseAsync = (_Err) => { + const fn = async (schema, value, _ctx, params) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); + captureStackTrace(e, params?.callee ?? fn); + throw e; + } + return result.value; + }; + return fn; +}; +const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +// registry mirrors of the compiler's sentinels, so this module never imports the compiler +const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); +const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); +// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. +const parse_validate = ((schema, value, _ctx) => { + const validator = schema._zod.bag.validator; + if (validator !== undefined && validator(value) !== COMPILE_INVALID) + return true; + return validateFallback(schema, value, _ctx); +}); +function validateFallback(schema, value, _ctx) { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const fallbackRun = schema._zod.bag.fallbackRun; + let result; + if (fallbackRun) { + // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound + ctx[COMPILE_FALLBACK] = true; + result = fallbackRun({ value, issues: [] }, ctx); + } + else { + result = schema._zod.run({ value, issues: [] }, ctx); + } + if (result instanceof Promise) { + throw new core.$ZodAsyncError(); + } + return result.issues.length === 0; +} +// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw +const parse_validateAsync = async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length === 0; +}; +const parse_encode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return parse(schema, value, ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const encode = /* @__PURE__*/ parse_encode($ZodRealError); +const parse_decode = (_Err) => { + const parse = parse_parse(_Err); + const fn = (schema, value, _ctx, _params) => { + return parse(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decode = /* @__PURE__*/ parse_decode($ZodRealError); +const parse_encodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); + }; + return fn; +}; +const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); +const parse_decodeAsync = (_Err) => { + const parseAsync = parse_parseAsync(_Err); + const fn = async (schema, value, _ctx, _params) => { + return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); + }; + return fn; +}; +const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); + +const versions_version = { + major: 4, + minor: 5, + patch: 4, +}; + + + + + + + + +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const defChecks = inst._zod.def.checks; + // if inst is itself a checks.$ZodCheck, run it as a check + const checks = inst._zod.traits.has("$ZodCheck") + ? [inst, ...(defChecks ?? [])] + : defChecks?.length + ? [...defChecks] + : []; + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + if (payload.memo) + return payload; + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + if (explicitlyAborted(payload)) + continue; + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + attachSchema(payload.issues, currLen, inst); + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } +}, { + // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. + get "~standard"() { + return hide(this, "~standard", standardProps(this)); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, +}); +/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ +const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; +function standardProps(inst) { + return { + validate: (value) => { + try { + return toStandardResult(safeParse(inst, value)); + } + catch (_) { + return safeParseAsync(inst, value).then(toStandardResult); + } + }, + vendor: "zod", + version: 1, + }; +} + +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } + else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +/** The `://` guard rejected the input before the URL constructor saw it. */ +const URL_BAD_FORMAT = 1; +/** The URL constructor rejected the input. */ +const URL_UNPARSEABLE = 2; +/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ +function parseURLObject(trimmed, def) { + // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted + if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { + return URL_BAD_FORMAT; + } + try { + // @ts-ignore + return new URL(trimmed); + } + catch { + return URL_UNPARSEABLE; + } +} +const asciiTabOrNewline = /[\t\n\r]/g; +/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ +function stripTabAndNewline(value) { + return value.replace(asciiTabOrNewline, ""); +} +function urlHostnameOk(url, hostname) { + hostname.lastIndex = 0; + return hostname.test(url.hostname); +} +function urlProtocolOk(url, protocol) { + protocol.lastIndex = 0; + return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); +} +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + const url = parseURLObject(trimmed, def); + if (url === URL_BAD_FORMAT) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid URL format", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (url === URL_UNPARSEABLE) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + return; + } + if (def.hostname && !urlHostnameOk(url, def.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + if (def.protocol && !urlProtocolOk(url, def.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + // Set the output value based on normalize flag + payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) + throw new Error(`Invalid nanoid length: ${def.length}`); + def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); + $ZodStringFormat.init(inst, def); +}); +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); + // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema + if (def.local || def.precision === -1) { + inst._zod.bag.laxFormat = true; + inst._zod.onattach.push((s) => { + s._zod.bag.laxFormat = true; + }); + } +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = regexes_date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = regexes_time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ +const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; +function isValidIPv6(value) { + if (!ipv6Alphabet.test(value)) + return false; + try { + // @ts-ignore + new URL(`http://[${value}]`); + return true; + } + catch { + return false; + } +} +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = regexes_ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + if (!isValidIPv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}))); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +function isValidCIDRv6(value) { + const parts = value.split("/"); + if (parts.length !== 2) + return false; + const [address, prefix] = parts; + if (!prefix) + return false; + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + return false; + if (prefixNum < 0 || prefixNum > 128) + return false; + return isValidIPv6(address); +} +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (!isValidCIDRv6(payload.value)) { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + // atob ignores whitespace, so reject it up front. + if (/\s/.test(data)) + return false; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!regexes_base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = regexes_base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodCreditCard ////////////////////////////// +const CC_SANITIZE = /[- ]/g; +/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ +function isLuhnAlgo(digits) { + let length = digits.length; + let bit = 1; + let sum = 0; + while (length) { + const value = +digits[--length]; + bit ^= 1; + sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; + } + return sum % 10 === 0; +} +function isValidCreditCard(input) { + if (!regexes.creditCard.test(input)) + return false; + return isLuhnAlgo(input.replace(CC_SANITIZE, "")); +} +const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { + // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. + def.pattern ?? (def.pattern = regexes.creditCard); + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidCreditCard(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "credit_card", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}))); +const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? String(input) + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}))); +const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { + checks.$ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}))); +const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes.undefined; + inst._zod.values = new Set([undefined]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}))); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input, optin, optout) { + const isPresent = key in input; + const isOptionalOut = optout === "optional"; + // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. + if (!isPresent && isOptionalOut && optin === "optional") { + return; + } + if (result.issues.length) { + // For optional-in/out schemas, ignore errors on absent keys. + if (optin !== undefined && isOptionalOut && !isPresent) { + return; + } + final.issues.push(...prefixIssues(key, result.issues)); + } + if (!isPresent && optin === undefined) { + if (!result.issues.length) { + final.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [key], + }); + } + return; + } + if (result.value === undefined) { + if (isPresent) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +// one shared instance; a fresh [] per schema cost 56 bytes retained +const NO_SYMBOL_KEYS = []; +function normalizeDef(def) { + const keys = Object.keys(def.shape); + const ownSymbols = Object.getOwnPropertySymbols(def.shape); + const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; + // aliases `keys` when there are no symbols, so a string-only shape keeps one array + const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; + for (const k of allKeys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + allKeys, + symbolKeys, + // string-only: handleCatchall matches it against `for...in`, which never yields a symbol + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + const optin = _catchall.optin; + const optout = _catchall.optout; + for (const key in input) { + // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. + if (keySet.has(key)) + continue; + // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. + if (key === "__proto__") { + if (t === "never") + unrecognized.push(key); + continue; + } + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. + continue: true, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. +const propShapes = new WeakMap(); +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + // const sh = def.shape; + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + propShapes.set(def, sh); + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh, + }); + propShapes.set(def, newSh); + return newSh; + }, + }); + } + const _normalized = util_cached(() => normalizeDef(def)); + defineLazyInternal(inst, "propValues", (zod) => { + const shape = zod.def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + if (!Object.prototype.hasOwnProperty.call(propValues, key)) { + assignProp(propValues, key, new Set()); + } + for (const v of field.values) + propValues[key].add(v); + // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. + if (field.optin !== undefined) + propValues[key].add(undefined); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value; + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const proms = []; + const shape = value.shape; + for (const key of value.allKeys) { + if (key === "__proto__") + continue; + const el = shape[key]; + const optin = el._zod.optin; + const optout = el._zod.optout; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); + } + else { + handlePropertyResult(r, payload, key, input, optin, optout); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = util_cached(() => normalizeDef(def)); + const memo = globalConfig.memoizer; + const generateFastpass = (shape) => { + const normalized = _normalized.value; + const syms = normalized.symbolKeys; + // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope + const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); + const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + // Prefixes in place, like util.prefixIssues does for every interpreted path. + const prefixStr = (id, k) => ` + for (let i = 0; i < ${id}.issues.length; i++) { + const iss = ${id}.issues[i]; + iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; + payload.issues.push(iss); + }`; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.allKeys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); + for (const key of normalized.allKeys) { + if (key === "__proto__") + continue; + const id = ids[key]; + const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); + const isPresent = `${k} in input`; + const schema = shape[key]; + const optin = schema?._zod?.optin; + const isOptionalIn = optin !== undefined; + const isOptionalOut = schema?._zod?.optout === "optional"; + doc.write(`const ${id} = ${parseStr(k)};`); + if (isOptionalIn && isOptionalOut) { + // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. + const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; + doc.write(` + const ${id}_present = ${isPresent}; + if (!${id}.issues.length || ${id}_present) { + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${assign}) { + newResult[${k}] = ${id}.value; + } + } + + `); + } + else if (!isOptionalIn) { + doc.write(` + const ${id}_present = ${isPresent}; + if (${id}.issues.length) {${prefixStr(id, k)} + } + if (!${id}_present && !${id}.issues.length) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: undefined, + path: [${k}] + }); + } + + if (${id}_present) { + newResult[${k}] = ${id}.value; + } + + `); + } + else { + doc.write(` + if (${id}.issues.length) {${prefixStr(id, k)} + } + + if (${id}.value === undefined) { + if (${isPresent}) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone + return doc.compile(); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") + ? "defaulted" + : zod.def.options.some((o) => o._zod.optin !== undefined) + ? "optional" + : undefined); + defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazyInternal(inst, "values", (zod) => { + if (zod.def.options.every((o) => o._zod.values)) { + return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + if (zod.def.options.every((o) => o._zod.pattern)) { + const patterns = zod.def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const matches = []; + for (let i = 0; i < results.length; i++) { + if (results[i].issues.length === 0) + matches.push(i); + } + if (matches.length === 1) { + final.value = results[matches[0]].value; + return final; + } + if (matches.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + matches, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const first = def.options.length === 1 ? def.options[0]._zod.run : null; + inst._zod.parse = (payload, ctx) => { + if (first) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}))); +/** Returns the option of `union` whose discriminator claims `value`. */ +function getDiscriminatedOption(union, value) { + const internals = union._zod; + let map = internals.bag.optionsMap; + if (!map) { + map = new Map(); + const { options, discriminator } = internals.def; + for (const option of options) { + // First declaration wins, matching the order the parse path resolves a duplicate in. + for (const v of option._zod.propValues?.[discriminator] ?? []) + if (!map.has(v)) + map.set(v, option); + } + internals.bag.optionsMap = map; + } + return map.get(value); +} +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazyInternal(inst, "propValues", (zod) => { + const propValues = {}; + for (const option of zod.def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!Object.prototype.hasOwnProperty.call(propValues, k)) { + assignProp(propValues, k, new Set()); + } + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. + def.options.forEach((option, i) => { + const propShape = propShapes.get(option._zod.def); + if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { + throw new Error(`Invalid discriminated union option at index "${i}"`); + } + }); + const disc = util_cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + // Fall back to union matching when the fast discriminator path fails: + // - explicitly enabled via unionFallback, or + // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions + if (def.unionFallback || ctx.direction === "backward") { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + options: Array.from(disc.value.keys()), + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function schemas_mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) + delete newObj.__proto__; + for (const key of sharedKeys) { + if (key === "__proto__") + continue; + const sharedValue = schemas_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = schemas_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. + const unrecKeys = new Map(); + let unrecIssue; + const keyIssues = new Map(); + const collect = (iss, side) => { + let keys; + if (iss.code === "unrecognized_keys" && !iss.path?.length) { + unrecIssue ?? (unrecIssue = iss); + keys = iss.keys; + } + else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { + const k = String(iss.path[0]); + if (!keyIssues.has(k)) + keyIssues.set(k, iss); + keys = [k]; + } + else { + return false; + } + for (const k of keys) { + if (!unrecKeys.has(k)) + unrecKeys.set(k, {}); + unrecKeys.get(k)[side] = true; + } + return true; + }; + for (const iss of left.issues) { + if (!collect(iss, "l")) + result.issues.push(iss); + } + for (const iss of right.issues) { + if (!collect(iss, "r")) + result.issues.push(iss); + } + // Report only keys rejected by BOTH sides + const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); + if (bothKeys.length) { + const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; + if (aggregated.length) + result.issues.push({ ...unrecIssue, keys: aggregated }); + for (const k of bothKeys) { + if (!aggregated.includes(k) && keyIssues.has(k)) + result.issues.push(keyIssues.get(k)); + } + } + const merged = schemas_mergeValues(left.value, right.value); + if (!merged.valid) { + if (aborted(result)) + return result; + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; + const proms = []; + const optinStart = getTupleOptStart(items, "optin"); + const optoutStart = getTupleOptStart(items, "optout"); + if (!def.rest) { + if (input.length < optinStart) { + payload.issues.push({ + code: "too_small", + minimum: optinStart, + inclusive: true, + input, + inst, + origin: "array", + }); + return payload; + } + if (input.length > items.length) { + payload.issues.push({ + code: "too_big", + maximum: items.length, + inclusive: true, + input, + inst, + origin: "array", + }); + } + } + // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. + const itemResults = new Array(items.length); + for (let i = 0; i < items.length; i++) { + const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((rr) => { + itemResults[i] = rr; + })); + } + else { + itemResults[i] = r; + } + } + if (def.rest) { + let i = items.length - 1; + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ value: el, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((r) => handleTupleResult(r, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); + } + return handleTupleResults(itemResults, payload, items, input, optoutStart); + }; +}))); +function getTupleOptStart(items, key) { + for (let i = items.length - 1; i >= 0; i--) { + // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. + const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; + if (!omittable) + return i + 1; + } + return 0; +} +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...util.prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +function handleTupleResults(itemResults, final, items, input, optoutStart) { + // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. + for (let i = 0; i < items.length; i++) { + const r = itemResults[i]; + const isPresent = i < input.length; + // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. + if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { + final.value.length = i; + break; + } + if (r.issues.length) { + if (!isPresent && i >= optoutStart) { + final.value.length = i; + break; + } + final.issues.push(...util.prefixIssues(i, r.issues)); + } + final.value[i] = r.value; + } + // Drop trailing slots that produced `undefined` for absent input + // (the array analog of an absent optional key on an object). The + // `i >= input.length` floor is critical: an explicit `undefined` + // *inside* the input must be preserved even when the schema is + // optional-out (e.g. `z.string().or(z.undefined())` accepting an + // explicit undefined value). + for (let i = final.value.length - 1; i >= input.length; i--) { + if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { + final.value.length = i; + } + else { + break; + } + } + return final; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + const memo = globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values && !def.partial) { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + // A declared __proto__ is stripped but is not an unrecognized key. + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + continue; + } + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + if (def.mode === "loose") { + // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into + if (key === "__proto__") + continue; + payload.value[key] = input[key]; + } + else { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + else { + payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; + // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. + let unrecognized; + // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + if (!Object.prototype.propertyIsEnumerable.call(input, key)) + continue; + let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals + const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; + if (checkNumericKey) { + const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); + if (retryResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (retryResult.issues.length === 0) { + keyResult = retryResult; + } + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else if (values) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + input: key, + path: [key], + inst, + }); + } + continue; + } + // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under + const outKey = keyResult.value; + if (outKey === "__proto__") + continue; + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[outKey] = result.value; + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + continue: true, + }); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + if (valueResult.issues.length) { + if (util.propertyKeyTypes.has(typeof key)) { + final.issues.push(...util.prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + const memo = core.globalConfig.memoizer; + memo?.attach(inst); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}))); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + const values = new Set(def.values); + inst._zod.values = values; + // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" + inst._zod.pattern = new RegExp(def.values.length + ? `^(${def.values + .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) + .join("|")})$` + : "^[^\\s\\S]$"); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}))); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + globalConfig.memoizer?.guard(inst); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(payload, result) { + // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. + payload.value = result.issues.length ? undefined : result.value; + return payload; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + inst._zod.optout = "optional"; + defineLazyInternal(inst, "values", (zod) => { + const values = zod.def.innerType._zod.values; + return values ? new Set([...values, undefined]) : undefined; + }); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (payload.value === undefined) { + // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. + if (def.innerType._zod.optin !== "defaulted") + return payload; + // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) + return result.then((result) => handleOptionalResult(payload, result)); + return handleOptionalResult(payload, result); + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { + // Call parent init - inherits optin/optout = "optional" + $ZodOptional.init(inst, def); + // Override values/pattern to NOT add undefined + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); + // Override parse to just delegate (no undefined handling) + inst._zod.parse = (payload, ctx) => { + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "pattern", (zod) => { + const pattern = zod.def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; + }); + defineLazyInternal(inst, "values", (zod) => { + return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "defaulted"; + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => { + const v = zod.def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new core.$ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}))); +function handleCatchResult(payload, result, def, ctx) { + if (!result.issues.length) { + payload.value = result.value; + // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. + if (result.memo) + payload.memo = true; + return payload; + } + // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. + payload.value = def.catchValue({ + ...result, + value: payload.value, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), + }, + input: payload.value, + }); + return payload; +} +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); + if (result instanceof Promise) { + return result.then((result) => handleCatchResult(payload, result, def, ctx)); + } + return handleCatchResult(payload, result, def, ctx); + }; +}); +const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}))); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. + if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); + util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); + util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); + util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}))); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { + $ZodPipe.init(inst, def); +}); +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); + defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); + defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); + defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. + if (!payload.memo) + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || util.primitiveTypes.has(typeof part)) { + regexParts.push(util.escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "string", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}))); +const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. + Object.defineProperty(inst, "_def", { value: def }); + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. + return Object.defineProperty(function (...args) { + const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return Object.defineProperty(async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }, "_zod", { value: inst._zod, enumerable: false }); + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}))); +const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}))); +const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. + defineLazy(inst._zod, "innerType", () => { + const d = def; + if (!d._cachedInner) + d._cachedInner = def.getter(); + return d._cachedInner; + }); + defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); + defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); + defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); + defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } +} + +var registries_a; +const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); +const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registries_registry() { + return new $ZodRegistry(); +} +(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + + + + + +// @__NO_SIDE_EFFECTS__ +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link _cuid2} instead. + * See https://github.com/paralleldrive/cuid. + */ +// @__NO_SIDE_EFFECTS__ +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _creditCard(Class, params) { + return new Class({ + type: "string", + format: "credit_card", + check: "string_format", + abort: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +const TimePrecision = (/* unused pure expression or super */ null && ({ + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +})); +// @__NO_SIDE_EFFECTS__ +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _any(Class) { + return new Class({ + type: "any", + }); +} +// @__NO_SIDE_EFFECTS__ +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +// @__NO_SIDE_EFFECTS__ +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _void(Class, params) { + return new Class({ + type: "void", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _date(Class, params) { + return new Class({ + type: "date", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _nan(Class, params) { + return new Class({ + type: "nan", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +// @__NO_SIDE_EFFECTS__ +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +// @__NO_SIDE_EFFECTS__ +function _positive(params) { + return _gt(0, params); +} +// negative +// @__NO_SIDE_EFFECTS__ +function _negative(params) { + return _lt(0, params); +} +// nonpositive +// @__NO_SIDE_EFFECTS__ +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +// @__NO_SIDE_EFFECTS__ +function _nonnegative(params) { + return _gte(0, params); +} +// @__NO_SIDE_EFFECTS__ +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxSize(maximum, params) { + return new checks.$ZodCheckMaxSize({ + check: "max_size", + ...util.normalizeParams(params), + maximum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _minSize(minimum, params) { + return new checks.$ZodCheckMinSize({ + check: "min_size", + ...util.normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _size(size, params) { + return new checks.$ZodCheckSizeEquals({ + check: "size_equals", + ...util.normalizeParams(params), + size, + }); +} +// @__NO_SIDE_EFFECTS__ +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum, + }); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum, + }); +} +// @__NO_SIDE_EFFECTS__ +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length, + }); +} +// @__NO_SIDE_EFFECTS__ +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern, + }); +} +// @__NO_SIDE_EFFECTS__ +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes, + }); +} +// @__NO_SIDE_EFFECTS__ +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix, + }); +} +// @__NO_SIDE_EFFECTS__ +function _property(property, schema, params) { + return new checks.$ZodCheckProperty({ + check: "property", + property, + schema, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _properties(shape) { + return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); +} +// @__NO_SIDE_EFFECTS__ +function _mime(types, params) { + return new checks.$ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +// @__NO_SIDE_EFFECTS__ +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +// @__NO_SIDE_EFFECTS__ +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +// @__NO_SIDE_EFFECTS__ +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +// @__NO_SIDE_EFFECTS__ +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +// @__NO_SIDE_EFFECTS__ +function _slugify() { + return _overwrite((input) => slugify(input)); +} +// @__NO_SIDE_EFFECTS__ +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...util.normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options: options, + discriminator, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +// @__NO_SIDE_EFFECTS__ +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof schemas.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _file(Class, params) { + return new Class({ + type: "file", + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +// @__NO_SIDE_EFFECTS__ +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); + }, + }); +} +// @__NO_SIDE_EFFECTS__ +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), + }); +} +// @__NO_SIDE_EFFECTS__ +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +// @__NO_SIDE_EFFECTS__ +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +// @__NO_SIDE_EFFECTS__ +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +// @__NO_SIDE_EFFECTS__ +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +// @__NO_SIDE_EFFECTS__ +function _custom(Class, fn, _params) { + const norm = util.normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +// @__NO_SIDE_EFFECTS__ +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params), + }); + return schema; +} +// @__NO_SIDE_EFFECTS__ +function _superRefine(fn, params) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }, params); + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +// @__NO_SIDE_EFFECTS__ +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function api_meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +// @__NO_SIDE_EFFECTS__ +function _stringbool(Classes, _params) { + const params = util.normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? schemas.$ZodCodec; + const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; + const _String = Classes.String ?? schemas.$ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + codec._zod.bag.truthy = truthyArray; + codec._zod.bag.falsy = falsyArray; + codec._zod.bag.case = params.case ?? "insensitive"; + return codec; +} +// @__NO_SIDE_EFFECTS__ +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = util.normalizeParams(_params); + const def = { + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + + + +function assignProps(target, ...sources) { + for (const source of sources) { + for (const key of Reflect.ownKeys(source)) { + if (Object.prototype.propertyIsEnumerable.call(source, key)) { + assignProp(target, key, source[key]); + } + } + } + return target; +} +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + sharedDefsExtractedFor: undefined, + sharedEmitDoneFor: undefined, + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + intersections: [], + deferred: [], + external: params?.external ?? undefined, + }; +} +/** + * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws + * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a + * custom JSON Schema was written into `json`, in which case the caller must not write its own. + */ +function handleUnrepresentable(schema, ctx, json, params, message) { + const result = typeof ctx.unrepresentable === "function" + ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) + : ctx.unrepresentable; + if (result === "any") + return false; + if (result === undefined || result === "throw") + throw new Error(message); + Object.assign(json, result); + return true; +} +function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + ctx.sharedDefsExtractedFor = undefined; + ctx.sharedEmitDoneFor = undefined; + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + const parent = schema._zod.parent; + if (parent) { + // Also set ref if processor didn't (for inheritance) + if (!result.ref) + result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + assignProps(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && "_prefault" in result.schema) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. +function encodeJSONPointerSegment(segment) { + return segment.replace(/~/g, "~0").replace(/\//g, "~1"); +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. + if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) + return; + // Track ids to detect duplicates across different schemas + const idToSchema = new Map(); + for (const entry of ctx.seen.entries()) { + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + const existing = idToSchema.get(id); + if (existing && existing !== entry[0]) { + throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); + } + idToSchema.set(id, entry[0]); + } + } + // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; + } + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` + if (entry[1] === root && !entry[1].schema.id) { + return { ref: uriPrefix }; + } + // self-contained schema + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; + }; + // stored cached version in `def` property remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; + } + } + } + if (ctx.external) + ctx.sharedDefsExtractedFor = ctx.external; +} +/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ +function compactTypeUnion(schema) { + const options = schema.anyOf; + if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) + return; + const types = []; + for (const option of options) { + if (!option || typeof option !== "object") + return; + // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. + compactTypeUnion(option); + const keys = Object.keys(option); + if (keys.length !== 1 || keys[0] !== "type") + return; + const type = option.type; + for (const member of Array.isArray(type) ? type : [type]) { + if (typeof member !== "string") + return; + if (!types.includes(member)) + types.push(member); + } + } + delete schema.anyOf; + // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. + schema.type = types.length === 1 ? types[0] : types; +} +/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, + * an annotation like `description` — makes a member unfoldable, so a constraint this does not + * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ +const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); +const UNION_KEYS = ["oneOf", "anyOf"]; +/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ +function undeclaredConstraint(member) { + const extra = member.additionalProperties; + if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) + return null; + return Object.keys(extra).length ? extra : null; +} +/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ +function foldObjects(members) { + const objects = []; + for (const member of members) { + // A boolean subschema is legal JSON Schema and carries no keywords to fold. + if (typeof member !== "object" || member.type !== "object") + return null; + for (const key in member) { + if (!FOLDABLE_KEYS.has(key)) + return null; + } + objects.push(member); + } + const properties = {}; + const required = new Set(); + for (const object of objects) { + for (const key in object.properties) { + // `in` would report a `__proto__` key as already present via the prototype chain and skip it. + if (Object.prototype.hasOwnProperty.call(properties, key)) + continue; + // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. + const parts = []; + for (const other of objects) { + const part = other.properties?.[key] ?? undeclaredConstraint(other); + if (part === null || part === undefined) + continue; + if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) + parts.push(part); + } + const merged = parts.length === 1 + ? parts[0] + : (foldObjects(parts) ?? { allOf: parts }); + assignProp(properties, key, merged); + } + for (const key of object.required ?? []) + required.add(key); + } + const folded = { type: "object", properties }; + if (required.size) + folded.required = [...required]; + // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. + if (objects.every((object) => object.additionalProperties === false)) { + folded.additionalProperties = false; + } + else { + const constraints = []; + for (const object of objects) { + const constraint = undeclaredConstraint(object); + if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) + constraints.push(constraint); + } + if (constraints.length === 1) + folded.additionalProperties = constraints[0]; + else if (constraints.length > 1) + folded.additionalProperties = { allOf: constraints }; + } + return folded; +} +/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two + * closed object members reject each other's keys and the schema validates nothing. Zod's parser + * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when + * *every* side rejects it — so the emitted schema has to pool them too, and folding the members + * into one object is the encoding that says so on every target. + * + * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` + * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it + * keeps its reference and its own closedness rather than being inlined as a stale copy. */ +function foldIntersection(json) { + const allOf = json.allOf; + if (!Array.isArray(allOf) || allOf.length < 2) + return; + // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. + for (const key of FOLDABLE_KEYS) + if (key in json) + return; + // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. + const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); + let folded = null; + if (!unions.length) { + folded = foldObjects(allOf); + } + else { + const union = unions[0]; + const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); + if (Object.keys(union).length !== 1) + return; + const rest = allOf.filter((m) => m !== union); + const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); + if (branches.some((b) => !b)) + return; + folded = { [keyword]: branches }; + } + if (!folded) + return; + delete json.allOf; + assignProps(json, folded); +} +function finalize(ctx, schema) { + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten refs - inherit properties from parent schemas + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + // already processed + if (seen.ref === null) + return; + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + const ref = seen.ref; + seen.ref = null; // prevent infinite recursion + if (ref) { + flattenRef(ref); + const refSeen = ctx.seen.get(ref); + const refSchema = refSeen.schema; + // merge referenced schema into current + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + // older drafts can't combine $ref with other properties + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + assignProps(schema, refSchema); + } + // restore child's own properties (child wins) + assignProps(schema, _cached); + const isParentRef = zodSchema._zod.parent === ref; + // For parent chain, child is a refinement - remove parent-only properties + if (isParentRef) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (!(key in _cached)) { + delete schema[key]; + } + } + } + // When ref was extracted to $defs, remove properties that match the definition + if (refSchema.$ref && refSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { + delete schema[key]; + } + } + } + } + // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced + const parent = zodSchema._zod.parent; + if (parent && parent !== ref) { + // Ensure parent is processed first so its def has inherited properties + flattenRef(parent); + const parentSeen = ctx.seen.get(parent); + if (parentSeen?.schema.$ref) { + schema.$ref = parentSeen.schema.$ref; + // De-duplicate with parent's definition + if (parentSeen.def) { + for (const key in schema) { + if (key === "$ref" || key === "allOf") + continue; + if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { + delete schema[key]; + } + } + } + } + } + // execute overrides + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + if (ctx.target !== "openapi-3.0") { + for (const entry of ctx.seen.entries()) { + compactTypeUnion(entry[1].def ?? entry[1].schema); + } + } + for (const rewrite of ctx.deferred) + rewrite(); + // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. + if (ctx.intersections.length) { + const carriers = new Map(); + for (const seen of ctx.seen.values()) { + for (const json of [seen.schema, seen.def]) { + const allOf = json?.allOf; + if (!Array.isArray(allOf)) + continue; + const existing = carriers.get(allOf); + if (existing) + existing.push(json); + else + carriers.set(allOf, [json]); + } + } + for (const allOf of ctx.intersections) { + for (const json of carriers.get(allOf) ?? []) + foldIntersection(json); + } + } + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs + assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); + // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). + const rootMetaId = ctx.metadataRegistry.get(schema)?.id; + if (rootMetaId !== undefined && result.id === rootMetaId) + delete result.id; + // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. + const defs = ctx.external?.defs ?? {}; + if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + if (seen.def.id === seen.defId) + delete seen.def.id; + assignProp(defs, seen.defId, seen.def); + } + } + } + if (ctx.external) + ctx.sharedEmitDoneFor = ctx.external; + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), + output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault" || + def.type === "catch") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + if (_schema._zod.traits.has("$ZodCodec")) + return true; + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + + + + +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids + if (format === "time" || laxFormat) { + delete json.format; + } + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const patternList = [...patterns]; + if (patternList.length === 1) + json.pattern = patternList[0].source; + else if (patternList.length > 1) { + json.allOf = [ + ...patternList.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + // when both minimum and exclusiveMinimum exist, pick the more restrictive one + const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); + const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); + const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; + if (exMin) { + if (legacy) { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + else if (typeof minimum === "number") { + json.minimum = minimum; + } + if (exMax) { + if (legacy) { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + else if (typeof maximum === "number") { + json.maximum = maximum; + } + if (typeof multipleOf === "number") { + // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. + if (Number.isFinite(multipleOf) && multipleOf !== 0) + json.multipleOf = Math.abs(multipleOf); + else + handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); + } +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); +}; +const symbolProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); +}; +const voidProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + // an empty enum accepts nothing, same as z.never() + if (values.length === 0) { + json.not = {}; + return; + } + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // a literal with no values accepts nothing, same as z.never() + if (def.values.length === 0) { + json.not = {}; + return; + } + const vals = []; + for (const val of def.values) { + if (val === undefined) { + // a custom schema replaces the whole literal, so there is nothing left to accumulate + if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) + return; + // otherwise do not add to vals + } + else if (typeof val === "bigint") { + if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) + return; + vals.push(Number(val)); + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } + else { + Object.assign(_json, file); // shared props at root + _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs + } + } + else { + Object.assign(_json, file); + } +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); +}; +const functionProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); +}; +const transformProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); +}; +const mapProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); +}; +const setProcessor = (schema, ctx, json, params) => { + handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { + ...params, + path: [...params.path, "items"], + }); +}; +// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an +// absent key, but their declared input type stays required. An input JSON Schema describes the +// declared type, so resolve past them to the schema that actually carries the optionality. +// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see +// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". +function inputOptin(schema) { + const def = schema._zod.def; + if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { + return inputOptin(def.out); + } + if (def.type === "catch") { + return inputOptin(def.innerType); + } + return schema._zod.optin; +} +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const shape = def.shape; + // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires + const symbolKeys = Object.getOwnPropertySymbols(shape); + if (symbolKeys.length && + handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { + return; + } + json.type = "object"; + json.properties = {}; + for (const key in shape) { + // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into + assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + })); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const field = def.shape[key]; + if (ctx.io === "input") { + return inputOptin(field) === undefined; + } + else { + return field._zod.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; + // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. + ctx.intersections.push(allOf); +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + let minItems = def.items.length; + while (minItems > 0) { + const item = def.items[minItems - 1]; + const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; + if (!optional) + break; + minItems--; + } + const maxItems = def.items.length; + const isClosed = !def.rest; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (isClosed) { + json.items = false; + } + else if (rest) { + json.items = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + else { + json.items = prefixItems; + if (isClosed) { + json.additionalItems = false; + } + else if (rest) { + json.additionalItems = rest; + } + if (minItems > 0) + json.minItems = minItems; + if (isClosed) + json.maxItems = maxItems; + } + // explicit user-defined length checks take precedence + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the + * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key + * behind a wrapper only carries its own `type` before then, and a union key only has its branches. + * + * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather + * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this + * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` + * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema + * outright. */ +function stringifyKeyNames(bySchema, json, visited) { + // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. + if (json.$ref) { + // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again + if (visited.has(json)) + return json; + visited.add(json); + const def = bySchema.get(json)?.def; + if (!def) + return json; + const inlined = stringifyKeyNames(bySchema, def, visited); + return inlined === def ? json : inlined; + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = json[keyword]; + if (!Array.isArray(branches)) + continue; + const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); + // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` + if (mapped.some((branch, i) => branch !== branches[i])) + json = { ...json, [keyword]: mapped }; + } + // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric + const types = Array.isArray(json.type) ? json.type : [json.type]; + const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); + // a heterogeneous key carries no type at all, so its numeric members are caught here instead + const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); + if (!numericType && !values?.some((v) => typeof v === "number")) + return json; + const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; + if (rest.enum) + rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); + else if (typeof rest.const === "number") + rest.const = String(rest.const); + // a heterogeneous key keeps its absent type: the stringified members already say what a key may be + if (!numericType) + return rest; + rest.type = "string"; + if (!values) + rest.pattern = (types.includes("number") ? number : integer).source; + return rest; +} +/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ +const pendingRecords = new WeakMap(); +function rewriteKeyNames(ctx) { + // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. + const bySchema = new Map(); + for (const entry of ctx.seen.values()) { + if (entry.def && !bySchema.has(entry.schema)) + bySchema.set(entry.schema, entry); + } + const rewrites = new Map(); + for (const record of pendingRecords.get(ctx) ?? []) { + const seen = ctx.seen.get(record); + const names = (seen?.def ?? seen?.schema)?.propertyNames; + if (!names || names === true || rewrites.has(names)) + continue; + const rewritten = stringifyKeyNames(bySchema, names, new Set()); + if (rewritten !== names) + rewrites.set(names, rewritten); + } + if (!rewrites.size) + return; + // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together + for (const entry of ctx.seen.values()) { + for (const carrier of [entry.schema, entry.def]) { + const rewritten = carrier && rewrites.get(carrier.propertyNames); + if (rewritten) + carrier.propertyNames = rewritten; + } + } +} +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) + const keyType = def.keyType; + const keyBag = keyType._zod.bag; + const patterns = keyBag?.patterns; + if (def.mode === "loose" && patterns && patterns.size > 0) { + // Use patternProperties for looseRecord with regex patterns + const valueSchema = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "patternProperties", "*"], + }); + json.patternProperties = {}; + for (const pattern of patterns) { + assignProp(json.patternProperties, pattern.source, valueSchema); + } + } + else { + // Default behavior: use propertyNames + additionalProperties + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + let pending = pendingRecords.get(ctx); + if (!pending) { + pending = []; + pendingRecords.set(ctx, pending); + ctx.deferred.push(() => rewriteKeyNames(ctx)); + } + pending.push(schema); + } + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } + // Add required for keys with discrete values (enum, literal, etc.) + const keyValues = keyType._zod.values; + // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. + const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; + if (keyValues && !def.partial && !omittableOnInput) { + const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); + if (validKeyValues.length > 0) { + json.required = validKeyValues.map(String); + } + } +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. + * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other + * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ +const UNREPRESENTABLE_DEFAULT = Symbol(); +function serializeDefaultValue(value, schema, ctx, json, params) { + let unrepresentable = false; + const serialized = JSON.stringify(value, (_, val) => { + if (typeof val !== "bigint") + return val; + unrepresentable = true; + return null; + }); + if (!unrepresentable) + return JSON.parse(serialized); + handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); + return UNREPRESENTABLE_DEFAULT; +} +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json.default = value; +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io !== "input") + return; + const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); + if (value !== UNREPRESENTABLE_DEFAULT) + json._prefault = value; +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); + return; + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const inIsTransform = def.in._zod.traits.has("$ZodTransform"); + const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + assignProp(schemas, key, finalize(ctx, schema)); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + + +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + map: { unit: "entries", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const FormatDictionary = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + credit_card: "credit card number", + jwt: "JWT", + template_literal: "input", + }; + // type names: missing keys = do not translate (use raw value via ?? fallback) + const TypeDictionary = { + // Compatibility: "nan" -> "NaN" for display + nan: "NaN", + // All other type names omitted - they fall back to raw values via ?? operator + }; + function getTypeName(type, input) { + if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { + return String(input); + } + return TypeDictionary[type] ?? type; + } + return (issue) => { + switch (issue.code) { + case "invalid_type": { + const expected = getTypeName(issue.expected); + const receivedType = parsedType(issue.input); + const received = getTypeName(receivedType, issue.input); + return `Invalid input: expected ${expected}, received ${received}`; + } + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { + const opts = issue.options.map((o) => `'${o}'`).join(" | "); + return `Invalid discriminator value. Expected ${opts}`; + } + if (issue.inclusive === false) { + return "Invalid input: more than one option matched"; + } + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* export default */ function en() { + return { + localeError: en_error(), + }; +} + + + + +/* Prototypes that already carry the lazy helper methods. Seeded with the + * intrinsics so that `init` on a foreign object — it accepts any object — + * can never install an accessor onto a prototype we do not own. */ +const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); +/* Helper methods live as non-enumerable lazy getters on the shared + * prototype instead of own properties on every instance. On first + * access the getter allocates the per-instance closure and caches it + * as a non-enumerable own property, so detached usage still works and + * the allocation only happens for methods actually touched. */ +function _lazyMethod(proto, key, make) { + Object.defineProperty(proto, key, { + configurable: true, + enumerable: false, + get() { + const value = make(this); + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + return value; + }, + set(value) { + Object.defineProperty(this, key, { value, configurable: true, writable: true }); + }, + }); +} +const classic_errors_initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + const proto = Object.getPrototypeOf(inst); + if (_installedErrorProtos.has(proto)) + return; + _installedErrorProtos.add(proto); + _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); + _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); + _lazyMethod(proto, "addIssue", (self) => (issue) => { + self.issues.push(issue); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + _lazyMethod(proto, "addIssues", (self) => (issues) => { + self.issues.push(...issues); + self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); + }); + Object.defineProperty(proto, "isEmpty", { + configurable: true, + enumerable: false, + get() { + return this.issues.length === 0; + }, + }); +}; +const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); +const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + + + +const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); +const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); +const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); + +// Codec functions +const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); +const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); +const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); +const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); +const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + + + + + + + + +// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. +function _ensureDefaultLocale() { + if (!globalConfig.localeError) + core_config(en()); +} +// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first +function _ensureDefaultMemoizer() { + if (!globalConfig.memoizer) + core_config({ memoizer: memoizer() }); +} +const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + _ensureDefaultLocale(); + $ZodType.init(inst, def); + inst.def = def; + inst.type = def.type; + return inst; +}, { + check(...chks) { + const def = this.def; + return this.clone(mergeDefs(def, { + checks: [ + ...(def.checks ?? []), + ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + }), { parent: true }); + }, + with(...chks) { + return this.check(...chks); + }, + clone(def, params) { + return clone(this, def, params); + }, + brand() { + return this; + }, + register(reg, meta) { + reg.add(this, meta); + return this; + }, + refine(check, params) { + return this.check(refine(check, params)); + }, + superRefine(refinement, params) { + return this.check(superRefine(refinement, params)); + }, + overwrite(fn) { + return this.check(_overwrite(fn)); + }, + optional() { + return schemas_optional(this); + }, + exactOptional() { + return exactOptional(this); + }, + nullable() { + return nullable(this); + }, + nullish() { + return schemas_optional(nullable(this)); + }, + nonoptional(params) { + return nonoptional(this, params); + }, + array() { + return schemas_array(this); + }, + or(arg) { + return schemas_union([this, arg]); + }, + and(arg) { + return intersection(this, arg); + }, + transform(tx) { + return pipe(this, transform(tx)); + }, + default(d) { + return schemas_default(this, d); + }, + prefault(d) { + return prefault(this, d); + }, + catch(params) { + return schemas_catch(this, params); + }, + pipe(target) { + return pipe(this, target); + }, + readonly() { + return readonly(this); + }, + describe(description) { + const cl = this.clone(); + globalRegistry.add(cl, { description }); + return cl; + }, + meta(...args) { + // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. + if (args.length === 0) + return globalRegistry.get(this); + const cl = this.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }, + isOptional() { + return this.safeParse(undefined).success; + }, + isNullable() { + return this.safeParse(null).success; + }, + apply(fn, ...args) { + return args.length === 0 ? fn(this) : fn(this, ...args); + }, + // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. + get "~standard"() { + return hide(this, "~standard", { + ...standardProps(this), + jsonSchema: { + input: createStandardJSONSchemaMethod(this, "input"), + output: createStandardJSONSchemaMethod(this, "output"), + }, + }); + }, + set "~standard"(value) { + util_own(this, "~standard", value); + }, + parse: function _parse(data, params) { + return classic_parse_parse(this, data, params, { callee: _parse }); + }, + parseAsync: async function _parseAsync(data, params) { + return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); + }, + safeParse(data, params) { + return parse_safeParse(this, data, params); + }, + async safeParseAsync(data, params) { + return parse_safeParseAsync(this, data, params); + }, + // `spa` is an alias: same function object as `safeParseAsync`, as before. + get spa() { + return this?.safeParseAsync; + }, + set spa(value) { + util_own(this, "spa", value); + }, + encode: function _encode(data, params) { + return classic_parse_encode(this, data, params, { callee: _encode }); + }, + decode: function _decode(data, params) { + return classic_parse_decode(this, data, params, { callee: _decode }); + }, + encodeAsync: async function _encodeAsync(data, params) { + return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); + }, + decodeAsync: async function _decodeAsync(data, params) { + return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); + }, + safeEncode(data, params) { + return parse_safeEncode(this, data, params); + }, + safeDecode(data, params) { + return parse_safeDecode(this, data, params); + }, + async safeEncodeAsync(data, params) { + return parse_safeEncodeAsync(this, data, params); + }, + async safeDecodeAsync(data, params) { + return parse_safeDecodeAsync(this, data, params); + }, + toJSONSchema(params) { + return createToJSONSchemaMethod(this, {})(params); + }, + // Reads through to the registry on every access, so it must not cache. + get description() { + return globalRegistry.get(this)?.description; + }, + // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. + get _def() { + return this._zod.def; + }, +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; +}, { + regex(...args) { + return this.check(_regex(...args)); + }, + includes(...args) { + return this.check(_includes(...args)); + }, + startsWith(...args) { + return this.check(_startsWith(...args)); + }, + endsWith(...args) { + return this.check(_endsWith(...args)); + }, + min(...args) { + return this.check(_minLength(...args)); + }, + max(...args) { + return this.check(_maxLength(...args)); + }, + length(...args) { + return this.check(_length(...args)); + }, + nonempty(...args) { + return this.check(_minLength(1, ...args)); + }, + lowercase(params) { + return this.check(_lowercase(params)); + }, + uppercase(params) { + return this.check(_uppercase(params)); + }, + trim() { + return this.check(_trim()); + }, + normalize(...args) { + return this.check(_normalize(...args)); + }, + toLowerCase() { + return this.check(_toLowerCase()); + }, + toUpperCase() { + return this.check(_toUpperCase()); + }, + slugify() { + return this.check(_slugify()); + }, +}); +const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); +}, { + email(params) { + return this.check(_email(ZodEmail, params)); + }, + url(params) { + return this.check(_url(ZodURL, params)); + }, + jwt(params) { + return this.check(_jwt(ZodJWT, params)); + }, + emoji(params) { + return this.check(api_emoji(ZodEmoji, params)); + }, + guid(params) { + return this.check(_guid(ZodGUID, params)); + }, + uuid(params) { + return this.check(_uuid(ZodUUID, params)); + }, + uuidv4(params) { + return this.check(_uuidv4(ZodUUID, params)); + }, + uuidv6(params) { + return this.check(_uuidv6(ZodUUID, params)); + }, + uuidv7(params) { + return this.check(_uuidv7(ZodUUID, params)); + }, + nanoid(params) { + return this.check(_nanoid(ZodNanoID, params)); + }, + cuid(params) { + return this.check(_cuid(ZodCUID, params)); + }, + cuid2(params) { + return this.check(_cuid2(ZodCUID2, params)); + }, + ulid(params) { + return this.check(_ulid(ZodULID, params)); + }, + base64(params) { + return this.check(_base64(ZodBase64, params)); + }, + base64url(params) { + return this.check(_base64url(ZodBase64URL, params)); + }, + xid(params) { + return this.check(_xid(ZodXID, params)); + }, + ksuid(params) { + return this.check(_ksuid(ZodKSUID, params)); + }, + ipv4(params) { + return this.check(_ipv4(ZodIPv4, params)); + }, + ipv6(params) { + return this.check(_ipv6(ZodIPv6, params)); + }, + cidrv4(params) { + return this.check(_cidrv4(ZodCIDRv4, params)); + }, + cidrv6(params) { + return this.check(_cidrv6(ZodCIDRv6, params)); + }, + e164(params) { + return this.check(_e164(ZodE164, params)); + }, + datetime(params) { + return this.check(_isoDateTime(ZodISODateTime, params)); + }, + date(params) { + return this.check(_isoDate(ZodISODate, params)); + }, + time(params) { + return this.check(_isoTime(schemas_ZodISOTime, params)); + }, + duration(params) { + return this.check(_isoDuration(schemas_ZodISODuration, params)); + }, +}); +function schemas_string(params) { + return _string(ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_email(params) { + return _email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_guid(params) { + return core._guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_uuid(params) { + return core._uuid(ZodUUID, params); +} +function uuidv4(params) { + return core._uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return core._uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function uuidv7(params) { + return core._uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return core._url(ZodURL, { + protocol: core.regexes.httpProtocol, + hostname: core.regexes.domain, + ...util.normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_emoji(params) { + return core._emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_nanoid(params) { + return core._nanoid(ZodNanoID, params); +} +/** + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link ZodCUID2} instead. + * See https://github.com/paralleldrive/cuid. + */ +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +/** + * Validates a CUID v1 string. + * + * @deprecated CUID v1 is deprecated by its authors due to information leakage + * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. + * See https://github.com/paralleldrive/cuid. + */ +function schemas_cuid(params) { + return core._cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid2(params) { + return core._cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ulid(params) { + return core._ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_xid(params) { + return core._xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ksuid(params) { + return core._ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv4(params) { + return core._ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_mac(params) { + return core._mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv6(params) { + return core._ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv4(params) { + return core._cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv6(params) { + return core._cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64(params) { + return core._base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64url(params) { + return core._base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_e164(params) { + return core._e164(ZodE164, params); +} +const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { + core.$ZodCreditCard.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function schemas_creditCard(params) { + return core._creditCard(ZodCreditCard, params); +} +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return core._jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + core.$ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}))); +function stringFormat(format, fnOrRegex, _params = {}) { + return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function schemas_hostname(_params) { + return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); +} +function schemas_hex(_params) { + return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); +} +function schemas_hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = core.regexes[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return core._stringFormat(ZodCustomStringFormat, format, regex, params); +} +const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}, { + gt(value, params) { + return this.check(_gt(value, params)); + }, + gte(value, params) { + return this.check(_gte(value, params)); + }, + min(value, params) { + return this.check(_gte(value, params)); + }, + lt(value, params) { + return this.check(_lt(value, params)); + }, + lte(value, params) { + return this.check(_lte(value, params)); + }, + max(value, params) { + return this.check(_lte(value, params)); + }, + int(params) { + return this.check(schemas_int(params)); + }, + safe(params) { + return this.check(schemas_int(params)); + }, + positive(params) { + return this.check(_gt(0, params)); + }, + nonnegative(params) { + return this.check(_gte(0, params)); + }, + negative(params) { + return this.check(_lt(0, params)); + }, + nonpositive(params) { + return this.check(_lte(0, params)); + }, + multipleOf(value, params) { + return this.check(_multipleOf(value, params)); + }, + step(value, params) { + return this.check(_multipleOf(value, params)); + }, + finite() { + return this; + }, +}); +function schemas_number(params) { + return _number(ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + ZodNumber.init(inst, def); +}); +function schemas_int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return core._float32(ZodNumberFormat, params); +} +function float64(params) { + return core._float64(ZodNumberFormat, params); +} +function int32(params) { + return core._int32(ZodNumberFormat, params); +} +function uint32(params) { + return core._uint32(ZodNumberFormat, params); +} +const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function schemas_boolean(params) { + return _boolean(ZodBoolean, params); +} +const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { + core.$ZodBigInt.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}, { + gte(value, params) { + return this.check(checks.gte(value, params)); + }, + min(value, params) { + return this.check(checks.gte(value, params)); + }, + gt(value, params) { + return this.check(checks.gt(value, params)); + }, + lt(value, params) { + return this.check(checks.lt(value, params)); + }, + lte(value, params) { + return this.check(checks.lte(value, params)); + }, + max(value, params) { + return this.check(checks.lte(value, params)); + }, + positive(params) { + return this.check(checks.gt(BigInt(0), params)); + }, + negative(params) { + return this.check(checks.lt(BigInt(0), params)); + }, + nonpositive(params) { + return this.check(checks.lte(BigInt(0), params)); + }, + nonnegative(params) { + return this.check(checks.gte(BigInt(0), params)); + }, + multipleOf(value, params) { + return this.check(checks.multipleOf(value, params)); + }, +}))); +function schemas_bigint(params) { + return core._bigint(ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { + core.$ZodBigIntFormat.init(inst, def); + ZodBigInt.init(inst, def); +}))); +function int64(params) { + return core._int64(ZodBigIntFormat, params); +} +function uint64(params) { + return core._uint64(ZodBigIntFormat, params); +} +const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { + core.$ZodSymbol.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); +}))); +function symbol(params) { + return core._symbol(ZodSymbol, params); +} +const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { + core.$ZodUndefined.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); +}))); +function schemas_undefined(params) { + return core._undefined(ZodUndefined, params); +} + +const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function schemas_null(params) { + return api_null(ZodNull, params); +} + +const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); +}); +function any() { + return _any(ZodAny); +} +const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(ZodUnknown); +} +const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function never(params) { + return _never(ZodNever, params); +} +const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { + core.$ZodVoid.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); +}))); +function schemas_void(params) { + return core._void(ZodVoid, params); +} + +const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { + core.$ZodDate.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(checks.gte(value, params)); + inst.max = (value, params) => inst.check(checks.lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}))); +function schemas_date(params) { + return core._date(ZodDate, params); +} +const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodArray.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; +}, { + min(n, params) { + return this.check(_minLength(n, params)); + }, + nonempty(params) { + return this.check(_minLength(1, params)); + }, + max(n, params) { + return this.check(_maxLength(n, params)); + }, + length(n, params) { + return this.check(_length(n, params)); + }, + unwrap() { + return this.element; + }, +}); +function schemas_array(element, params) { + return _array(ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); +} +const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodObjectJIT.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); +}, { + keyof() { + return schemas_enum(Object.keys(this._zod.def.shape)); + }, + catchall(catchall) { + return this.clone({ ...this._zod.def, catchall: catchall }); + }, + passthrough() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + loose() { + return this.clone({ ...this._zod.def, catchall: unknown() }); + }, + strict() { + return this.clone({ ...this._zod.def, catchall: never() }); + }, + strip() { + return this.clone({ ...this._zod.def, catchall: undefined }); + }, + extend(incoming) { + return extend(this, incoming); + }, + safeExtend(incoming) { + return safeExtend(this, incoming); + }, + merge(other) { + return merge(this, other); + }, + pick(mask) { + return pick(this, mask); + }, + omit(mask) { + return omit(this, mask); + }, + partial(...args) { + return partial(ZodOptional, this, args[0]); + }, + exactPartial(...args) { + return partial(ZodExactOptional, this, args[0], "exactPartial"); + }, + required(...args) { + return util_required(ZodNonOptional, this, args[0]); + }, +}); +function schemas_object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params), + }; + return new ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: never(), + ...util.normalizeParams(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params), + }); +} +const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function schemas_union(options, params) { + return new ZodUnion({ + type: "union", + options: options, + ...normalizeParams(params), + }); +} +const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { + ZodUnion.init(inst, def); + core.$ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}))); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...util.normalizeParams(params), + }); +} +const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new ZodDiscriminatedUnion({ + type: "union", + options: options, + discriminator, + ...normalizeParams(params), + }); +} +const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodTuple.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); +}, { + rest(rest) { + return this.clone({ + ...this._zod.def, + rest: rest, + }); + }, + partial() { + const def = this._zod.def; + // a refinement was authored against the full arity; partialing would run it on a shorter array + if (def.checks?.length) + throw new Error(".partial() cannot be used on tuple schemas containing refinements"); + return this.clone({ + ...def, + items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), + }); + }, +}))); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof core.$ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new ZodTuple({ + type: "tuple", + items: items, + rest, + ...util.normalizeParams(params), + }); +} +const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodRecord.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function schemas_record(keyType, valueType, params) { + // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() + if (!valueType || !valueType._zod) { + return new ZodRecord({ + type: "record", + keyType: schemas_string(), + valueType: keyType, + ...normalizeParams(valueType), + }); + } + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...util.normalizeParams(params), + partial: true, + }); +} +function looseRecord(keyType, valueType, params) { + return new ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...util.normalizeParams(params), + }); +} +const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodMap.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_map(keyType, valueType, params) { + return new ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { + _ensureDefaultMemoizer(); + core.$ZodSet.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(core._minSize(...args)); + inst.nonempty = (params) => inst.check(core._minSize(1, params)); + inst.max = (...args) => inst.check(core._maxSize(...args)); + inst.size = (...args) => inst.check(core._size(...args)); +}))); +function schemas_set(valueType, params) { + return new ZodSet({ + type: "set", + valueType: valueType, + ...util.normalizeParams(params), + }); +} +const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; +}); +function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new ZodEnum({ + type: "enum", + entries, + ...util.normalizeParams(params), + }); +} +const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { + core.$ZodFile.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(core._minSize(size, params)); + inst.max = (size, params) => inst.check(core._maxSize(size, params)); + inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); +}))); +function schemas_file(params) { + return core._file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + _ensureDefaultMemoizer(); + $ZodTransform.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + if (!("input" in _issue)) + _issue.input = payload.value; + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function schemas_optional(innerType) { + return new ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { + $ZodExactOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function exactOptional(innerType) { + return new ZodExactOptional({ + type: "optional", + innerType: innerType, + }); +} +const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function schemas_nullish(innerType) { + return schemas_optional(nullable(innerType)); +} +const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function schemas_default(innerType, defaultValue) { + return new ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params), + }); +} +const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { + core.$ZodSuccess.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function schemas_catch(innerType, catchValue) { + return new ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), + }); +} + +const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { + core.$ZodNaN.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); +}))); +function nan(params) { + return core._nan(ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + core.$ZodCodec.init(inst, def); +}))); +function schemas_codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +function invertCodec(codec) { + const def = codec._zod.def; + return new ZodCodec({ + type: "pipe", + in: def.out, + out: def.in, + transform: def.reverseTransform, + reverseTransform: def.transform, + }); +} +const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { + ZodPipe.init(inst, def); + $ZodPreprocess.init(inst, def); +}); +const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { + core.$ZodTemplateLiteral.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); +}))); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...util.normalizeParams(params), + }); +} +const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { + core.$ZodPromise.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}))); +function schemas_promise(innerType) { + return new ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { + core.$ZodFunction.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); +}))); +function _function(params) { + return new ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +// custom checks +function schemas_check(fn) { + const ch = new core.$ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function custom(fn, _params) { + return core._custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn, params) { + return _superRefine(fn, params); +} +// Re-export describe and meta from core +const schemas_describe = describe; +const schemas_meta = api_meta; +function _instanceof(cls, params = {}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...util.normalizeParams(params), + }); + inst._zod.bag.Class = cls; + // Override check to emit invalid_type instead of custom + inst._zod.check = (payload) => { + if (!(payload.value instanceof cls)) { + payload.issues.push({ + code: "invalid_type", + expected: cls.name, + input: payload.value, + inst, + path: [...(inst._zod.def.path ?? [])], + }); + } + }; + return inst; +} + +// stringbool +const stringbool = (...args) => core._stringbool({ + Codec: ZodCodec, + Boolean: ZodBoolean, + String: ZodString, +}, ...args); +function schemas_json(params) { + const jsonSchema = lazy(() => { + return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +function preprocess(fn, schema) { + return new ZodPreprocess({ + type: "pipe", + in: transform(fn), + out: schema, + }); +} + + + + +function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); +} +function iso_date(params) { + return _isoDate(ZodISODate, params); +} +function iso_time(params) { + return core._isoTime(ZodISOTime, params); +} +function iso_duration(params) { + return core._isoDuration(ZodISODuration, params); +} + +// Zod 3 compat layer + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +const ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom", +}; + +/** @deprecated Use `z.config(params)` instead. */ +function setErrorMap(map) { + core.config({ + customError: map, + }); +} +/** @deprecated Use `z.config()` instead. */ +function getErrorMap() { + return core.config().customError; +} +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var compat_ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { +})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); + + + +function coerce_string(params) { + return core._coercedString(schemas.ZodString, params); +} +function coerce_number(params) { + return _coercedNumber(ZodNumber, params); +} +function coerce_boolean(params) { + return core._coercedBoolean(schemas.ZodBoolean, params); +} +function coerce_bigint(params) { + return core._coercedBigint(schemas.ZodBigInt, params); +} +function coerce_date(params) { + return core._coercedDate(schemas.ZodDate, params); +} + + + +//#region src/constants.ts +const LATEST_PROTOCOL_VERSION = "2025-11-25"; +const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; +const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ + LATEST_PROTOCOL_VERSION, + "2025-06-18", + "2025-03-26", + "2024-11-05", + "2024-10-07" +]; +/** +* `_meta` key associating a message with a 2025-11-25 task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; +/** +* `_meta` key carrying the MCP protocol version governing a request. +* +* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. +*/ +const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; +/** +* `_meta` key identifying the client software making a request. +* +* Clients SHOULD include it on every request; the value is self-reported and +* intended for display, logging, and debugging — servers should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; +/** +* `_meta` key identifying the server software producing a response. +* +* Servers SHOULD include it on every response; the value is self-reported and +* intended for display, logging, and debugging — clients should not rely on +* it for behavior or security decisions. +*/ +const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; +/** +* `_meta` key carrying the client's capabilities for a request. +* +* Capabilities are declared per request rather than once at initialization; +* servers must not infer capabilities from prior requests. +*/ +const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; +/** +* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request +* that opened the stream a notification was delivered on. +* +* Stamped by the server on every notification delivered via a +* `subscriptions/listen` stream (including the leading +* `notifications/subscriptions/acknowledged`); on stdio, where all messages +* share one channel, clients use it to correlate notifications with their +* originating subscription. The value is the listen request's JSON-RPC ID +* verbatim. +*/ +const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; +/** +* `_meta` key carrying the desired log level for a request. +* +* When absent, the server must not send `notifications/message` notifications +* for the request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. +*/ +const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; +/** +* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `traceparent` header format, +* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. +* +* @see https://www.w3.org/TR/trace-context/#traceparent-header +*/ +const TRACEPARENT_META_KEY = "traceparent"; +/** +* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C `tracestate` header format, +* e.g. `vendor1=value1,vendor2=value2`. +* +* @see https://www.w3.org/TR/trace-context/#tracestate-header +*/ +const TRACESTATE_META_KEY = "tracestate"; +/** +* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). +* +* When present, the value MUST follow the W3C Baggage header format, +* e.g. `userId=alice,serverRegion=us-east-1`. +* +* @see https://www.w3.org/TR/baggage/ +*/ +const BAGGAGE_META_KEY = "baggage"; +const JSONRPC_VERSION = "2.0"; +const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); +const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); +const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); +const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); +const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); + +//#endregion +//#region src/schemas.ts +const JSONValueSchema = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema), + schemas_array(JSONValueSchema) +])); +const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); +const JSONArraySchema = schemas_array(JSONValueSchema); +/** +* A progress token, used to associate progress notifications with the original request. +*/ +const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* An opaque token used to represent a cursor for pagination. +*/ +const CursorSchema = schemas_string(); +/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ +const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); +/** +* Metadata for associating messages with a task. +* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); +const RequestMetaSchema = looseObject({ + progressToken: ProgressTokenSchema.optional(), + [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() +}); +/** +* Common params for any request. +*/ +const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +/** +* Common params for any task-augmented request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); +const RequestSchema = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema.loose().optional() +}); +const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); +const NotificationSchema = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema.loose().optional() +}); +/** +* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). +* Loose — implementation-specific keys pass through. +* +* The serverInfo key identifies the server software producing the response +* (servers SHOULD include it on every response; the value is self-reported +* and intended for display, logging, and debugging). The getter defers the +* `ImplementationSchema` reference, which is declared later in this file. +*/ +const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { + return ImplementationSchema.optional().catch(void 0); +} }); +const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); +/** +* A uniquely identifying ID for a request in JSON-RPC. +*/ +const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); +/** +* A request that expects a response. +*/ +const JSONRPCRequestSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + ...RequestSchema.shape +}).strict(); +/** +* A notification which does not expect a response. +*/ +const JSONRPCNotificationSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + ...NotificationSchema.shape +}).strict(); +/** +* A successful (non-error) response to a request. +*/ +const JSONRPCResultResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema, + result: ResultSchema +}).strict(); +/** +* A response to a request that indicates an error occurred. +*/ +const JSONRPCErrorResponseSchema = schemas_object({ + jsonrpc: literal(JSONRPC_VERSION), + id: RequestIdSchema.optional(), + error: schemas_object({ + code: schemas_number().int(), + message: schemas_string(), + data: unknown().optional() + }) +}).strict(); +const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ + JSONRPCRequestSchema, + JSONRPCNotificationSchema, + JSONRPCResultResponseSchema, + JSONRPCErrorResponseSchema +]); +const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); +/** +* A response that indicates success but carries no data. +*/ +const EmptyResultSchema = ResultSchema.strict(); +const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ + requestId: RequestIdSchema.optional(), + reason: schemas_string().optional() +}); +/** +* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. +* +* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. +* +* This notification indicates that the result will be unused, so any associated processing SHOULD cease. +* +* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. +*/ +const CancelledNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema +}); +/** +* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. +*/ +const IconSchema = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() +}); +/** +* Base schema to add `icons` property. +* +*/ +const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); +/** +* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. +*/ +const BaseMetadataSchema = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() +}); +/** +* Describes the name and version of an MCP implementation. +*/ +const ImplementationSchema = BaseMetadataSchema.extend({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() +}); +const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); +const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; +}, intersection(schemas_object({ + form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema.optional() +}), JSONObjectSchema.optional())); +/** +* Task capabilities for clients, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ClientTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() + }).optional() +}); +/** +* Task capabilities for servers, indicating which request types support task creation. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ServerTasksCapabilitySchema = looseObject({ + list: JSONObjectSchema.optional(), + cancel: JSONObjectSchema.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() +}); +/** +* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. +*/ +const ClientCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + sampling: schemas_object({ + context: JSONObjectSchema.optional(), + tools: JSONObjectSchema.optional() + }).optional(), + elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema, + clientInfo: ImplementationSchema +}); +/** +* This request is sent from the client to the server when it first connects, asking it to begin initialization. +*/ +const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema +}); +/** +* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. +*/ +const ServerCapabilitiesSchema = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), + logging: JSONObjectSchema.optional(), + completions: JSONObjectSchema.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() +}); +/** +* After receiving an initialize request from the client, the server sends this response. +*/ +const InitializeResultSchema = ResultSchema.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema, + serverInfo: ImplementationSchema, + instructions: schemas_string().optional() +}); +/** +* This notification is sent from the client to the server after initialization has finished. +*/ +const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema.optional() +}); +/** +* A request from the client asking the server to advertise its supported protocol +* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers +* MUST implement `server/discover`. Clients MAY call it but are not required to — +* version negotiation can also happen inline via the per-request `_meta` envelope. +*/ +const DiscoverRequestSchema = RequestSchema.extend({ + method: literal("server/discover"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The result returned by the server for a `server/discover` request. +*/ +const DiscoverResultSchema = ResultSchema.extend({ + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilitiesSchema, + instructions: schemas_string().optional() +}); +/** +* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. +*/ +const PingRequestSchema = RequestSchema.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema.optional() +}); +const ProgressSchema = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) +}); +const ProgressNotificationParamsSchema = schemas_object({ + ...NotificationsParamsSchema.shape, + ...ProgressSchema.shape, + progressToken: ProgressTokenSchema +}); +/** +* An out-of-band notification used to inform the receiver of a progress update for a long-running request. +* +* @category notifications/progress +*/ +const ProgressNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema +}); +const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); +const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); +const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); +/** +* The contents of a specific resource or sub-resource. +*/ +const ResourceContentsSchema = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); +/** +* A Zod schema for validating Base64 strings that is more performant and +* robust for very large inputs than the default regex-based check. It avoids +* stack overflows by using the native `atob` function for validation. +*/ +const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } +}, { message: "Invalid Base64 string" }); +const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); +/** +* The sender or recipient of messages and data in a conversation. +*/ +const RoleSchema = schemas_enum(["user", "assistant"]); +/** +* Optional annotations providing clients additional context about a resource. +*/ +const AnnotationsSchema = schemas_object({ + audience: schemas_array(RoleSchema).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() +}); +/** +* A known resource that the server is capable of reading. +*/ +const ResourceSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* A template description for resources available on the server. +*/ +const ResourceTemplateSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema.optional(), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of resources the server has. +*/ +const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); +/** +* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. +*/ +const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); +/** +* Sent from the client to request a list of resource templates the server has. +*/ +const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); +/** +* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. +*/ +const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); +const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); +/** +* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. +*/ +const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to the server, to read a specific resource URI. +*/ +const ReadResourceRequestSchema = RequestSchema.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema +}); +/** +* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. +*/ +const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); +/** +* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ResourceListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema.optional() +}); +const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. +*/ +const SubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema +}); +const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; +/** +* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const UnsubscribeRequestSchema = RequestSchema.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema +}); +/** +* The set of notification types a client opts in to on a `subscriptions/listen` +* request. Each type is opt-in; the server MUST NOT send a notification type +* the client has not explicitly requested here. +*/ +const SubscriptionFilterSchema = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() +}); +const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent from the client to open a long-lived channel for receiving notifications +* outside the context of a specific request (protocol revision 2026-07-28). +* Replaces the previous HTTP GET endpoint and `resources/subscribe`. +*/ +const SubscriptionsListenRequestSchema = RequestSchema.extend({ + method: literal("subscriptions/listen"), + params: SubscriptionsListenRequestParamsSchema +}); +const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); +/** +* Sent by the server as the first message on a `subscriptions/listen` stream +* to acknowledge that the subscription has been established and report which +* notification types it agreed to honor (protocol revision 2026-07-28). +*/ +const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/subscriptions/acknowledged"), + params: SubscriptionsAcknowledgedNotificationParamsSchema +}); +/** +* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's +* JSON-RPC ID under the canonical subscription-id key (mirroring the same key +* on every notification delivered on the stream). Extends +* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed +* here too. +*/ +const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); +/** +* The response to a `subscriptions/listen` request, signalling that the +* subscription has ended gracefully (for example, during server shutdown). +* Because the listen stream is long-lived, this result is sent only when the +* server tears the subscription down; an abrupt transport close carries no +* response. The result body is otherwise empty. +*/ +const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); +/** +* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. +*/ +const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); +/** +* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. +*/ +const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema +}); +/** +* Describes an argument that a prompt can accept. +*/ +const PromptArgumentSchema = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) +}); +/** +* A prompt or prompt template that the server offers. +*/ +const PromptSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema)), + _meta: schemas_optional(looseObject({})) +}); +/** +* Sent from the client to request a list of prompts and prompt templates the server has. +*/ +const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); +/** +* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. +*/ +const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); +/** +* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. +*/ +const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() +}); +/** +* Used by the client to get a prompt provided by the server. +*/ +const GetPromptRequestSchema = RequestSchema.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema +}); +/** +* Text provided to or from an LLM. +*/ +const TextContentSchema = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* An image provided to or from an LLM. +*/ +const ImageContentSchema = schemas_object({ + type: literal("image"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Audio content provided to or from an LLM. +*/ +const AudioContentSchema = schemas_object({ + type: literal("audio"), + data: auth_CUe6YdwF_Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A tool call request from an assistant (LLM). +* Represents the assistant's request to use a tool. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolUseContentSchema = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* The contents of a resource, embedded into a prompt or tool call result. +*/ +const EmbeddedResourceSchema = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), + annotations: AnnotationsSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* A resource that the server is capable of reading, included in a prompt or tool call result. +* +* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. +*/ +const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); +/** +* A content block that can be used in prompts and tool results. +*/ +const ContentBlockSchema = schemas_union([ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ResourceLinkSchema, + EmbeddedResourceSchema +]); +/** +* Describes a message returned as part of a prompt. +*/ +const PromptMessageSchema = schemas_object({ + role: RoleSchema, + content: ContentBlockSchema +}); +/** +* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. +*/ +const GetPromptResultSchema = ResultSchema.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema) +}); +/** +* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const PromptListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Additional properties describing a `Tool` to clients. +* +* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. +* They are not guaranteed to provide a faithful description of +* tool behavior (including descriptive properties like `title`). +* +* Clients should never make tool use decisions based on `ToolAnnotations` +* received from untrusted servers. +*/ +const ToolAnnotationsSchema = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() +}); +/** +* Execution-related properties for a tool. +*/ +const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" +]).optional() }); +/** +* Definition for a tool the client can call. +*/ +const ToolSchema = schemas_object({ + ...BaseMetadataSchema.shape, + ...IconsSchema.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema.optional(), + execution: ToolExecutionSchema.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the client to request a list of tools the server has. +*/ +const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); +/** +* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. +*/ +const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); +/** +* The server's response to a tool call. +*/ +const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ + content: schemas_array(ContentBlockSchema).default([]), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() +}); +/** +* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. +*/ +const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); +/** +* Parameters for a `tools/call` request. +*/ +const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Used by the client to invoke a tool provided by the server. +*/ +const CallToolRequestSchema = RequestSchema.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema +}); +/** +* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. +*/ +const ToolListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Base schema for list changed subscription options (without callback). +* Used internally for Zod validation of `autoRefresh` and `debounceMs`. +*/ +const ListChangedOptionsBaseSchema = schemas_object({ + autoRefresh: schemas_boolean().default(true), + debounceMs: schemas_number().int().nonnegative().default(300) +}); +/** +* The severity of a log message. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingLevelSchema = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" +]); +/** +* Parameters for a `logging/setLevel` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); +/** +* A request from the client to the server, to enable or adjust logging. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const SetLevelRequestSchema = RequestSchema.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema +}); +/** +* Parameters for a `notifications/message` notification. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ + level: LoggingLevelSchema, + logger: schemas_string().optional(), + data: unknown() +}); +/** +* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to stderr logging +* (STDIO servers) or OpenTelemetry. +*/ +const LoggingMessageNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema +}); +/** +* Hints to use for model selection. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); +/** +* The server's preferences for model selection, requested of the client during sampling. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ModelPreferencesSchema = schemas_object({ + hints: schemas_array(ModelHintSchema).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() +}); +/** +* Controls tool usage behavior in sampling requests. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" +]).optional() }); +/** +* The result of a tool execution, provided by the user (server). +* Represents the outcome of invoking a tool requested via `ToolUseContent`. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const ToolResultContentSchema = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Basic content types for sampling responses (without tool use). +* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingContentSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema +]); +/** +* Content block types allowed in sampling messages. +* This includes text, image, audio, tool use requests, and tool results. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ + TextContentSchema, + ImageContentSchema, + AudioContentSchema, + ToolUseContentSchema, + ToolResultContentSchema +]); +/** +* Describes a message issued to or received from an LLM API. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const SamplingMessageSchema = schemas_object({ + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Parameters for a `sampling/createMessage` request. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + messages: schemas_array(SamplingMessageSchema), + modelPreferences: ModelPreferencesSchema.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema.optional(), + tools: schemas_array(ToolSchema).optional(), + toolChoice: ToolChoiceSchema.optional() +}); +/** +* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageRequestSchema = RequestSchema.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema +}); +/** +* The client's response to a `sampling/create_message` request from the server. +* This is the backwards-compatible version that returns single content (no arrays). +* Used when the request does not include tools. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema, + content: SamplingContentSchema +}); +/** +* The client's response to a `sampling/create_message` request when tools were provided. +* This version supports array content for tool use flows. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to calling LLM +* provider APIs directly. +*/ +const CreateMessageResultWithToolsSchema = ResultSchema.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema, + content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) +}); +/** +* Primitive schema definition for boolean fields. +*/ +const BooleanSchemaSchema = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() +}); +/** +* Primitive schema definition for string fields. +*/ +const StringSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() +}); +/** +* Primitive schema definition for number fields. +*/ +const NumberSchemaSchema = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() +}); +/** +* Schema for single-selection enumeration without display titles for options. +*/ +const UntitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() +}); +/** +* Schema for single-selection enumeration with display titles for each option. +*/ +const TitledSingleSelectEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() +}); +/** +* Use {@linkcode TitledSingleSelectEnumSchema} instead. +* This interface will be removed in a future version. +*/ +const LegacyTitledEnumSchemaSchema = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() +}); +const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); +/** +* Schema for multiple-selection enumeration without display titles for options. +*/ +const UntitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Schema for multiple-selection enumeration with display titles for each option. +*/ +const TitledMultiSelectEnumSchemaSchema = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() +}); +/** +* Combined schema for multiple-selection enumeration +*/ +const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); +/** +* Primitive schema definition for enum fields. +*/ +const EnumSchemaSchema = schemas_union([ + LegacyTitledEnumSchemaSchema, + SingleSelectEnumSchemaSchema, + MultiSelectEnumSchemaSchema +]); +/** +* Union of all primitive schema definitions. +*/ +const PrimitiveSchemaDefinitionSchema = schemas_union([ + EnumSchemaSchema, + BooleanSchemaSchema, + StringSchemaSchema, + NumberSchemaSchema +]); +/** +* Parameters for an `elicitation/create` request for form-based elicitation. +*/ +const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) +}); +/** +* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. +*/ +const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() +}); +/** +* The parameters for a request to elicit additional information from the user via the client. +*/ +const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); +/** +* A request from the server to elicit user input via the client. +* The client should present the message and form fields to the user (form mode) +* or navigate to a URL (URL mode). +*/ +const ElicitRequestSchema = RequestSchema.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema +}); +/** +* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); +/** +* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. +* +* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome +* of an out-of-band interaction by retrying the original request; no server-initiated +* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow +* only. The 2026-07-28 wire codec excludes this notification. +* @category notifications/elicitation/complete +*/ +const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema +}); +/** +* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. +*/ +const ElicitResultSchema = ResultSchema.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) +}); +/** +* A reference to a resource or resource template definition. +*/ +const ResourceTemplateReferenceSchema = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() +}); +/** +* Identifies a prompt. +*/ +const PromptReferenceSchema = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() +}); +/** +* Parameters for a {@linkcode CompleteRequest | completion/complete} request. +*/ +const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ + ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() +}); +/** +* A request from the client to the server, to ask for completion options. +*/ +const CompleteRequestSchema = RequestSchema.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema +}); +/** +* The server's response to a {@linkcode CompleteRequest | completion/complete} request +*/ +const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) +}) }); +/** +* Represents a root directory or file that the server can operate on. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootSchema = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() +}); +/** +* Sent from the server to request a list of root URIs from the client. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsRequestSchema = RequestSchema.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema.optional() +}); +/** +* The client's response to a `roots/list` request from the server. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); +/** +* A notification from the client to the server, informing it that the list of roots has changed. +* +* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains +* in the specification for at least twelve months. Migrate to passing paths via +* tool parameters, resource URIs, or configuration. +*/ +const RootsListChangedNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema.optional() +}); +/** +* Task creation parameters, used to ask that the server create a task to represent a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskCreationParamsSchema = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() +}); +/** +* The status of a task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusSchema = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" +]); +/** +* A pollable state object associated with a request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskSchema = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) +}); +/** +* Result returned when a task is created, containing the task data wrapped in a `task` field. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); +/** +* Parameters for task status notification. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); +/** +* A notification sent when a task's status changes. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const TaskStatusNotificationSchema = NotificationSchema.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema +}); +/** +* A request to get the state of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode GetTaskRequest | tasks/get} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskResultSchema = ResultSchema.merge(TaskSchema); +/** +* A request to get the result of a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadRequestSchema = RequestSchema.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a `tasks/result` request. +* The structure matches the result type of the original request. +* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. +* +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const GetTaskPayloadResultSchema = ResultSchema.loose(); +/** +* A request to list tasks. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); +/** +* The response to a {@linkcode ListTasksRequest | tasks/list} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); +/** +* A request to cancel a specific task. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskRequestSchema = RequestSchema.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) +}); +/** +* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. +* +* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. +*/ +const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); +const ClientRequestSchema = schemas_union([ + PingRequestSchema, + auth_CUe6YdwF_InitializeRequestSchema, + DiscoverRequestSchema, + CompleteRequestSchema, + SetLevelRequestSchema, + GetPromptRequestSchema, + ListPromptsRequestSchema, + ListResourcesRequestSchema, + ListResourceTemplatesRequestSchema, + ReadResourceRequestSchema, + SubscribeRequestSchema, + UnsubscribeRequestSchema, + SubscriptionsListenRequestSchema, + CallToolRequestSchema, + ListToolsRequestSchema +]); +const ClientNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + auth_CUe6YdwF_InitializedNotificationSchema, + RootsListChangedNotificationSchema +]); +const ClientResultSchema = schemas_union([ + EmptyResultSchema, + CreateMessageResultSchema, + CreateMessageResultWithToolsSchema, + ElicitResultSchema, + ListRootsResultSchema +]); +const ServerRequestSchema = schemas_union([ + PingRequestSchema, + CreateMessageRequestSchema, + ElicitRequestSchema, + ListRootsRequestSchema +]); +const ServerNotificationSchema = schemas_union([ + CancelledNotificationSchema, + ProgressNotificationSchema, + LoggingMessageNotificationSchema, + ResourceUpdatedNotificationSchema, + ResourceListChangedNotificationSchema, + ToolListChangedNotificationSchema, + PromptListChangedNotificationSchema, + SubscriptionsAcknowledgedNotificationSchema, + ElicitationCompleteNotificationSchema +]); +const ServerResultSchema = schemas_union([ + EmptyResultSchema, + InitializeResultSchema, + DiscoverResultSchema, + CompleteResultSchema, + GetPromptResultSchema, + ListPromptsResultSchema, + ListResourcesResultSchema, + ListResourceTemplatesResultSchema, + ReadResourceResultSchema, + auth_CUe6YdwF_CallToolResultSchema, + ListToolsResultSchema, + SubscriptionsListenResultSchema +]); + +//#endregion +//#region src/auth.ts +/** +* Reusable URL validation that disallows `javascript:` scheme +*/ +const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { + if (!URL.canParse(val)) { + ctx.addIssue({ + code: ZodIssueCode.custom, + message: "URL must be parseable", + fatal: true + }); + return NEVER; + } +}).refine((url) => { + const u = new URL(url); + return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; +}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); +/** +* RFC 9728 OAuth Protected Resource Metadata +*/ +const OAuthProtectedResourceMetadataSchema = looseObject({ + resource: schemas_string().url(), + authorization_servers: schemas_array(SafeUrlSchema).optional(), + jwks_uri: schemas_string().url().optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + bearer_methods_supported: schemas_array(schemas_string()).optional(), + resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + resource_name: schemas_string().optional(), + resource_documentation: schemas_string().optional(), + resource_policy_uri: schemas_string().url().optional(), + resource_tos_uri: schemas_string().url().optional(), + tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), + authorization_details_types_supported: schemas_array(schemas_string()).optional(), + dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + dpop_bound_access_tokens_required: schemas_boolean().optional() +}); +/** +* RFC 8414 OAuth 2.0 Authorization Server Metadata +*/ +const OAuthMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + service_documentation: SafeUrlSchema.optional(), + revocation_endpoint: SafeUrlSchema.optional(), + revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint: schemas_string().optional(), + introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + code_challenge_methods_supported: schemas_array(schemas_string()).optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery 1.0 Provider Metadata +* +* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata +*/ +const OpenIdProviderMetadataSchema = looseObject({ + issuer: schemas_string(), + authorization_endpoint: SafeUrlSchema, + token_endpoint: SafeUrlSchema, + userinfo_endpoint: SafeUrlSchema.optional(), + jwks_uri: SafeUrlSchema, + registration_endpoint: SafeUrlSchema.optional(), + scopes_supported: schemas_array(schemas_string()).optional(), + response_types_supported: schemas_array(schemas_string()), + response_modes_supported: schemas_array(schemas_string()).optional(), + grant_types_supported: schemas_array(schemas_string()).optional(), + acr_values_supported: schemas_array(schemas_string()).optional(), + subject_types_supported: schemas_array(schemas_string()), + id_token_signing_alg_values_supported: schemas_array(schemas_string()), + id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), + request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), + token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), + display_values_supported: schemas_array(schemas_string()).optional(), + claim_types_supported: schemas_array(schemas_string()).optional(), + claims_supported: schemas_array(schemas_string()).optional(), + service_documentation: schemas_string().optional(), + claims_locales_supported: schemas_array(schemas_string()).optional(), + ui_locales_supported: schemas_array(schemas_string()).optional(), + claims_parameter_supported: schemas_boolean().optional(), + request_parameter_supported: schemas_boolean().optional(), + request_uri_parameter_supported: schemas_boolean().optional(), + require_request_uri_registration: schemas_boolean().optional(), + op_policy_uri: SafeUrlSchema.optional(), + op_tos_uri: SafeUrlSchema.optional(), + client_id_metadata_document_supported: schemas_boolean().optional(), + authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) +}); +/** +* OpenID Connect Discovery metadata that may include OAuth 2.0 fields +* This schema represents the real-world scenario where OIDC providers +* return a mix of OpenID Connect and OAuth 2.0 metadata fields +*/ +const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ + ...OpenIdProviderMetadataSchema.shape, + ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape +}); +/** +* OAuth 2.1 token response +*/ +const OAuthTokensSchema = schemas_object({ + access_token: schemas_string(), + id_token: schemas_string().optional(), + token_type: schemas_string(), + expires_in: coerce_number().optional(), + scope: schemas_string().optional(), + refresh_token: schemas_string().optional() +}).strip(); +/** +* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. +* +* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when +* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, +* so strict checking rejects conformant IdPs. +*/ +const IdJagTokenExchangeResponseSchema = schemas_object({ + issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), + access_token: schemas_string(), + token_type: schemas_string().optional(), + expires_in: schemas_number().optional(), + scope: schemas_string().optional() +}).strip(); +/** +* OAuth 2.1 error response +*/ +const OAuthErrorResponseSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional(), + error_uri: schemas_string().optional() +}); +/** +* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` +*/ +const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata +*/ +const OAuthClientMetadataSchema = schemas_object({ + redirect_uris: schemas_array(SafeUrlSchema), + token_endpoint_auth_method: schemas_string().optional(), + grant_types: schemas_array(schemas_string()).optional(), + response_types: schemas_array(schemas_string()).optional(), + application_type: schemas_string().optional(), + client_name: schemas_string().optional(), + client_uri: SafeUrlSchema.optional(), + logo_uri: OptionalSafeUrlSchema, + scope: schemas_string().optional(), + contacts: schemas_array(schemas_string()).optional(), + tos_uri: OptionalSafeUrlSchema, + policy_uri: schemas_string().optional(), + jwks_uri: SafeUrlSchema.optional(), + jwks: any().optional(), + software_id: schemas_string().optional(), + software_version: schemas_string().optional(), + software_statement: schemas_string().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration client information +*/ +const OAuthClientInformationSchema = schemas_object({ + client_id: schemas_string(), + client_secret: schemas_string().optional(), + client_id_issued_at: schemas_number().optional(), + client_secret_expires_at: schemas_number().optional() +}).strip(); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) +*/ +const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); +/** +* RFC 7591 OAuth 2.0 Dynamic Client Registration error response +*/ +const OAuthClientRegistrationErrorSchema = schemas_object({ + error: schemas_string(), + error_description: schemas_string().optional() +}).strip(); +/** +* RFC 7009 OAuth 2.0 Token Revocation request +*/ +const OAuthTokenRevocationRequestSchema = schemas_object({ + token: schemas_string(), + token_type_hint: schemas_string().optional() +}).strip(); + +//#endregion + +//# sourceMappingURL=auth-CUe6YdwF.mjs.map + + + + + + + + +//#region ../core-internal/src/errors/crossBundleBrand.ts +/** +* Cross-bundle `instanceof` support for the SDK error classes. +* +* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their +* own copy of `core-internal`, so an error constructed by one package fails a +* prototype-identity `instanceof` against the same class re-exported by the other — +* exactly the check a dual-role process (gateway, host, in-process test) writes. +* +* Instead of prototype identity, branded classes stamp every instance with the brand +* strings of its class chain under a registry symbol (`Symbol.for`, shared across +* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the +* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior +* is unchanged for anything unbranded. +* +* A class participates by defining an **own** `mcpBrand` static (via a `static {}` +* block, so nothing reaches the declaration files — a declared `protected static` +* field would make the constructor types nominally incompatible across the bundled +* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as +* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand +* keep plain prototype semantics — a foreign base-class instance never satisfies +* `instanceof UserSubclass`. +* +* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core +* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), +* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios +* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a +* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 +* (Symbol.hasInstance on every schema class for cross-version interop). +* +* Contract notes: +* - Participation criterion: **every error class exported from a public package that +* callers are documented to `instanceof` must be branded.** The per-package +* errorBrandConformance tests walk the export surfaces and fail naming any +* exported Error subclass that has not opted in. +* - Brands assert **identity, not shape**: brand strings are version-less, so an +* instance from one SDK version matches the class of another. Members added to a +* branded class in a later version may be absent on a matched instance — read +* fields defensively, and treat branded classes as additive-only. The escape +* hatch when a release must break a branded class's read contract: change that +* class's brand string in the same release, which cleanly severs cross-version +* matching for that class. The per-package brand pins make the rename +* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each +* package's errorBrandConformance test pins its package-local ones. +* - Cross-bundle matching requires **both** copies to be at or after the release +* that introduced branding; against an older copy, behavior degrades to plain +* prototype `instanceof` in both directions. +* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would +* break the brand statics; default esbuild/webpack/terser settings do not. +*/ +/** Registry symbol — identical across bundled copies and realms. */ +const BRANDS = Symbol.for("mcp.sdk.errorBrands"); +/** +* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an +* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — +* subclasses inherit the stamping without touching their constructors. +* +* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would +* satisfy `instanceof` while lacking the prototype members (getters like `.status`) +* that callers reach for after the check. +*/ +function stampErrorBrands(instance, ctor) { + const brands = /* @__PURE__ */ new Set(); + let current = ctor; + while (typeof current === "function") { + const brand = current.mcpBrand; + if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); + current = Object.getPrototypeOf(current); + } + if (brands.size === 0) return; + Object.defineProperty(instance, BRANDS, { + value: brands, + enumerable: false, + configurable: true + }); +} +/** +* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the +* value carries the **own** brand of the class being tested against (cross-bundle +* path), falling back to ordinary prototype-based `instanceof` otherwise. +*/ +function brandedHasInstance(cls, value) { + try { + if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { + const carried = value[BRANDS]; + if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; + } + } catch {} + return Function.prototype[Symbol.hasInstance].call(cls, value); +} + +//#endregion +//#region ../core-internal/src/auth/errors.ts +/** +* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} +* and extensions. +*/ +let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { + /** + * The request is missing a required parameter, includes an invalid parameter value, + * includes a parameter more than once, or is otherwise malformed. + */ + OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; + /** + * Client authentication failed (e.g., unknown client, no client authentication included, + * or unsupported authentication method). + */ + OAuthErrorCode$1["InvalidClient"] = "invalid_client"; + /** + * The provided authorization grant or refresh token is invalid, expired, revoked, + * does not match the redirection URI used in the authorization request, or was issued to another client. + */ + OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; + /** + * The authenticated client is not authorized to use this authorization grant type. + */ + OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; + /** + * The authorization grant type is not supported by the authorization server. + */ + OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; + /** + * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. + */ + OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; + /** + * The resource owner or authorization server denied the request. + */ + OAuthErrorCode$1["AccessDenied"] = "access_denied"; + /** + * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. + */ + OAuthErrorCode$1["ServerError"] = "server_error"; + /** + * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. + */ + OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; + /** + * The authorization server does not support obtaining an authorization code using this method. + */ + OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; + /** + * The authorization server does not support the requested token type. + */ + OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; + /** + * The access token provided is expired, revoked, malformed, or invalid for other reasons. + */ + OAuthErrorCode$1["InvalidToken"] = "invalid_token"; + /** + * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) + */ + OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; + /** + * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) + */ + OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; + /** + * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) + */ + OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; + /** + * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) + */ + OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; + /** + * The request requires higher privileges than provided by the access token. + */ + OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; + /** + * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) + */ + OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; + return OAuthErrorCode$1; +}({}))); +/** +* OAuth error class for all OAuth-related errors. +*/ +var src_CX2iR2pK_OAuthError = class OAuthError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, errorUri) { + super(message); + this.code = code; + this.errorUri = errorUri; + this.name = "OAuthError"; + stampErrorBrands(this, new.target); + } + /** + * Converts the error to a standard OAuth error response object. + */ + toResponseObject() { + const response = { + error: this.code, + error_description: this.message + }; + if (this.errorUri) response.error_uri = this.errorUri; + return response; + } + /** + * Creates an {@linkcode OAuthError} from an OAuth error response. + */ + static fromResponse(response) { + return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); + } +}; + +//#endregion +//#region ../core-internal/src/errors/sdkErrors.ts +/** +* Error codes for SDK errors (local errors that never cross the wire). +* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses +* descriptive string values for better developer experience. +* +* These errors are thrown locally by the SDK and are never serialized as +* JSON-RPC error responses. +*/ +let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { + /** Transport is not connected */ + SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; + /** Transport is already connected */ + SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; + /** Protocol is not initialized */ + SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; + /** Required capability is not supported by the remote side */ + SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; + /** Request timed out waiting for response */ + SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; + /** Connection was closed */ + SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; + /** Failed to send message */ + SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; + /** Response result failed local schema validation */ + SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; + /** + * The response carried a `resultType` discriminator (protocol revision + * 2026-07-28) naming a result kind this client cannot consume yet, e.g. + * `input_required`. The kind is carried in `data.resultType`. + */ + SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; + /** + * The multi-round-trip auto-fulfilment driver exhausted its round cap + * (`inputRequired.maxRounds`) without the server returning a complete + * result. `data.rounds` carries the cap that was hit and + * `data.lastResult` carries the last `input_required` payload received + * (`{ inputRequests, requestState? }`), so callers can inspect or resume + * the flow manually. + */ + SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; + /** + * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / + * `listResources()` / `listResourceTemplates()` walk hit the + * `ClientOptions.listMaxPages` cap without the server's pagination + * converging. `data.method` carries the list verb and + * `data.listMaxPages` the cap that was hit; raise the cap or fall back to + * explicit per-page `{ cursor }` calls. + */ + SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; + /** + * The spec method being sent does not exist on the negotiated protocol + * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or + * `server/discover` toward a 2025-era peer). Raised locally, before + * anything reaches the transport. The method and era are carried in + * `data.method` / `data.era`. + */ + SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; + /** + * Protocol-era negotiation at connect time failed without producing either a + * usable modern (2026-07-28+) era or a definitive legacy fallback signal — + * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a + * network failure, or the server answered the probe with a 5xx (a typed + * connect error, never an era verdict). + * + * Negotiation-phase only: this code is never used once an era is + * established. Auth walls never carry it: a 401/403 rejecting the probe + * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} + * instead, so era-recovery flows keyed on this code (e.g. cached-verdict + * gateways) can never persist a verdict for an unauthorized exchange. + */ + SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; + SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; + /** + * HTTP 401 authentication failure: the transport's re-auth retry still got + * 401 (`Server returned 401 after re-authentication`), or the version + * negotiation probe was rejected 401 with no `authProvider` configured + * (`Version negotiation failed: the server requires authorization (HTTP 401)`). + * Carried on an {@linkcode SdkHttpError} with `status: 401`. + */ + SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; + /** + * HTTP 403 denial: the step-up re-authorization retry limit was reached, + * or the version negotiation probe was rejected 403 + * (`Version negotiation failed: the server denied access (HTTP 403)`). + * Carried on an {@linkcode SdkHttpError} with `status: 403`. + */ + SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; + SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; + SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; + SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; + return SdkErrorCode$1; +}({}); +/** +* SDK errors are local errors that never cross the wire. +* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors +* that are serialized and sent as error responses. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" +* try { +* // Throwing an SDK error +* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); +* } catch (error) { +* // Checking error type by code +* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { +* // Handle timeout +* } +* } +* ``` +*/ +var src_CX2iR2pK_SdkError = class extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "SdkError"; + stampErrorBrands(this, new.target); + } +}; +/** +* An {@linkcode SdkError} subclass for HTTP transport failures. +* +* Thrown by the streamable HTTP transport when the server responds with a +* non-OK status code. Narrows {@linkcode SdkError.data | data} to +* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status +* without unsafe casting. +* +* @example +* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" +* if (error instanceof SdkHttpError) { +* console.log(error.status); // number +* console.log(error.statusText); // string | undefined +* } +* ``` +*/ +var SdkHttpError = class extends src_CX2iR2pK_SdkError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); + } + constructor(code, message, data) { + super(code, message, data); + this.name = "SdkHttpError"; + } + get status() { + return this.data.status; + } + get statusText() { + return this.data.statusText; + } +}; + +//#endregion +//#region ../core-internal/src/shared/authUtils.ts +/** +* Utilities for handling OAuth resource URIs. +*/ +/** +* Converts a server URL to a resource URL by removing the fragment. +* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} +* states that resource URIs "MUST NOT include a fragment component". +* Keeps everything else unchanged (scheme, domain, port, path, query). +*/ +function resourceUrlFromServerUrl(url) { + const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); + resourceURL.hash = ""; + return resourceURL; +} +/** +* Checks if a requested resource URL matches a configured resource URL. +* A requested resource matches if it has the same scheme, domain, port, +* and its path starts with the configured resource's path. +* +* @param options - The options object +* @param options.requestedResource - The resource URL being requested +* @param options.configuredResource - The resource URL that has been configured +* @returns true if the requested resource matches the configured resource, false otherwise +*/ +function checkResourceAllowed({ requestedResource, configuredResource }) { + const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); + const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); + if (requested.origin !== configured.origin) return false; + if (requested.pathname.length < configured.pathname.length) return false; + const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; + const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; + return requestedPath.startsWith(configuredPath); +} + +//#endregion +//#region ../core-internal/src/shared/clientCapabilityRequirements.ts +/** +* Inbound request methods whose processing structurally requires a client +* capability, keyed by method, valued by the capabilities required. +* +* Currently empty: none of the request methods served on the 2026-07-28 +* registry unconditionally requires a client capability. Entries appear here +* when such methods exist — for example requests whose handling embeds +* elicitation or sampling input requests (the input-request engine), or +* opt-in subscription delivery. Handler-conditional requirements (a specific +* tool that needs sampling) are not expressible as a static method table and +* are enforced at the point the requirement arises instead. +*/ +const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); +/** +* The client capabilities a request method structurally requires, or +* `undefined` when the method has no static requirement. +*/ +function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { + return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; +} +function isPlainObject$7(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Whether a required nested member counts as declared even though it is not +* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at +* all) is read as form support — the pre-mode (2025) meaning of a bare +* declaration — so an `elicitation.form` requirement treats it as satisfied. +* Declaring any mode explicitly (for example `elicitation: { url: {} }`) +* removes the implication. +*/ +function isImpliedCapabilityMember(capability, member, declaredValue) { + return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; +} +/** +* The client capabilities an embedded multi-round-trip input request requires +* (call site 2 — the outbound input-request leg): a server MUST NOT send an +* `inputRequests` kind the request's declared client capabilities do not +* cover. Returns `undefined` for entries whose method is not one of the +* embedded input-request kinds (those are a server bug handled separately, +* not a capability question). +* +* The requirement is mode-aware where the capability is: URL-mode elicitation +* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires +* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a +* mode the client did not declare); sampling with `tools`/`toolChoice` +* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies +* the form requirement — see {@linkcode missingClientCapabilities}. +*/ +function requiredClientCapabilitiesForInputRequest(entry) { + switch (entry.method) { + case "elicitation/create": + if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; + return { elicitation: { form: {} } }; + case "sampling/createMessage": { + const params = entry.params; + if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; + return { sampling: {} }; + } + case "roots/list": return { roots: {} }; + default: return; + } +} +/** +* Computes the subset of `required` client capabilities the client did not +* declare. Returns `undefined` when every required capability is declared; +* otherwise returns an object in the `ClientCapabilities` shape containing +* exactly the missing capabilities (suitable for +* `data.requiredCapabilities` on the `-32021` error). +* +* A capability counts as declared when its top-level key is present on the +* declared capabilities; when the requirement names nested members (for +* example `elicitation: { url: {} }`), each named member must also be present +* under the declared capability. One lenient reading applies: a bare +* `elicitation: {}` declaration (no mode sub-capability at all) counts as +* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare +* declaration. An absent or empty `declared` value means +* nothing is declared — every required capability is missing (the structural +* clean-refusal posture for sessions with no per-request capability view). +*/ +function src_CX2iR2pK_missingClientCapabilities(required, declared) { + const missing = {}; + for (const [capability, requirement] of Object.entries(required)) { + if (requirement === void 0) continue; + const declaredValue = declared === void 0 ? void 0 : declared[capability]; + if (declaredValue === void 0) { + missing[capability] = requirement; + continue; + } + if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { + const missingMembers = {}; + for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; + if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; + } + } + return Object.keys(missing).length > 0 ? missing : void 0; +} + +//#endregion +//#region ../core-internal/src/shared/protocolEras.ts +/** +* The first protocol revision of the modern (2026-07-28) era. Revision identifiers +* are ISO dates, so lexicographic comparison orders them chronologically. +*/ +const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; +/** +* Modern-era protocol revisions this SDK can negotiate via `server/discover`. +* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy +* `initialize` list), so adding a revision here can never leak a modern version +* string into a 2025-era handshake. Internal — not part of the public API surface. +*/ +const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); +/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ +function isModernProtocolVersion(version) { + return version >= FIRST_MODERN_PROTOCOL_VERSION; +} +/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ +function legacyProtocolVersions(versions) { + return versions.filter((version) => !isModernProtocolVersion(version)); +} +/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ +function modernProtocolVersions(versions) { + return versions.filter((version) => isModernProtocolVersion(version)); +} + +//#endregion +//#region ../core-internal/src/wire/textFallback.ts +/** +* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH +* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` +* is a non-object value (array/primitive/`null`) and the handler authored no +* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. +* Object-shaped (or absent) `structuredContent` returns the same reference. +* +* Leaf module: imported by both era codec modules, so it must NOT import from +* `./codec.js` (which value-imports the rev codecs at top level — that would +* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec +* module first). +*/ +function appendTextFallbackForNonObject(result) { + const sc = result.structuredContent; + if (sc === void 0) return result; + if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; + if (result.content?.some((c) => c.type === "text") ?? false) return result; + return { + ...result, + content: [...result.content ?? [], { + type: "text", + text: JSON.stringify(sc) + }] + }; +} + +//#endregion +//#region ../core-internal/src/wire/resultFamilies.ts +/** +* Result-family keys that must never default into a `{content: []}` tools/call +* success. Shared by the 2025 wire-seam schema and server normalization. +* Leaf module (like `textFallback.ts`): imported by registry/server paths, so +* it must NOT import from `./codec.js` — that would close a runtime cycle. +*/ +const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ + "task", + "inputRequests", + "requestState" +]; +/** +* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and +* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. +*/ +function normalizeContentlessToolResult(value) { + if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; + return { + ...value, + content: [] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts +/** +* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from +* the public/neutral types/schemas.ts. The neutral layer is the public-API +* superset and is free to evolve (e.g., SEP-2106 widening); this file is the +* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. +* +* This is the era's complete frozen wire-parse contract — both the 2025-only +* delta (the deprecated task family, the era role unions) AND frozen copies of +* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, +* prompts/resources/completion/elicitation, …). The 2026-era codec +* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. +* +* The 2025-only delta (the task message surface, restored types-only by #2248 +* for interop with task-capable 2025 peers) is parsed ONLY through this era's +* registry; the deprecated Task* schemas also live (marked `@deprecated`) in +* the neutral schema layer so the public types stay nameable without a +* cross-layer import — nameability is constant, runtime availability is +* version-keyed — but appear in no API signature. Q1 increment 2 — deletions +* are physical: the +* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do +* carry the deprecated Task* sub-schemas by composition — soft contamination, +* tracked for anchor-exactness adjudication). +* +* The only cross-layer dependency is `import type { JSONObject, JSONValue }` +* from the neutral types barrel — pure structural type aliases with no parse +* behavior. No runtime schema is shared with the neutral layer. +*/ +function build$1() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** + * Metadata for associating messages with a task. + * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + /** + * Common params for any request. + */ + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** + * Common params for any task-augmented request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const RequestSchema$1 = schemas_object({ + method: schemas_string(), + params: BaseRequestParamsSchema$1.loose().optional() + }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * A response that indicates success but carries no data. + */ + const EmptyResultSchema$1 = ResultSchema$1.strict(); + const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + requestId: RequestIdSchema$1.optional(), + reason: schemas_string().optional() + }); + /** + * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. + * + * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. + * + * This notification indicates that the result will be unused, so any associated processing SHOULD cease. + * + * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. + */ + const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + /** + * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. + */ + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + /** + * Base schema to add `icons` property. + * + */ + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + /** + * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. + */ + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + /** + * Describes the name and version of an MCP implementation. + */ + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** + * Task capabilities for clients, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** + * Task capabilities for servers, indicating which request types support task creation. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + /** + * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. + */ + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ClientCapabilitiesSchema$1, + clientInfo: ImplementationSchema$1 + }); + /** + * This request is sent from the client to the server when it first connects, asking it to begin initialization. + */ + const InitializeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("initialize"), + params: InitializeRequestParamsSchema$1 + }); + /** + * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. + */ + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + /** + * After receiving an initialize request from the client, the server sends this response. + */ + const InitializeResultSchema$1 = ResultSchema$1.extend({ + protocolVersion: schemas_string(), + capabilities: ServerCapabilitiesSchema$1, + serverInfo: ImplementationSchema$1, + instructions: schemas_string().optional() + }); + /** + * This notification is sent from the client to the server after initialization has finished. + */ + const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/initialized"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. + */ + const PingRequestSchema$1 = RequestSchema$1.extend({ + method: literal("ping"), + params: BaseRequestParamsSchema$1.optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + /** + * An out-of-band notification used to inform the receiver of a progress update for a long-running request. + * + * @category notifications/progress + */ + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); + const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); + const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); + /** + * The contents of a specific resource or sub-resource. + */ + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * Optional annotations providing clients additional context about a resource. + */ + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + /** + * A known resource that the server is capable of reading. + */ + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * A template description for resources available on the server. + */ + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of resources the server has. + */ + const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); + /** + * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. + */ + const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); + /** + * Sent from the client to request a list of resource templates the server has. + */ + const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); + /** + * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. + */ + const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); + const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); + /** + * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. + */ + const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to the server, to read a specific resource URI. + */ + const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/read"), + params: ReadResourceRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. + */ + const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); + /** + * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. + */ + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. + */ + const SubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/subscribe"), + params: SubscribeRequestParamsSchema$1 + }); + const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; + /** + * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ + method: literal("resources/unsubscribe"), + params: UnsubscribeRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. + */ + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + /** + * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. + */ + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + /** + * Describes an argument that a prompt can accept. + */ + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + /** + * A prompt or prompt template that the server offers. + */ + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + /** + * Sent from the client to request a list of prompts and prompt templates the server has. + */ + const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); + /** + * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. + */ + const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); + /** + * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. + */ + const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }); + /** + * Used by the client to get a prompt provided by the server. + */ + const GetPromptRequestSchema$1 = RequestSchema$1.extend({ + method: literal("prompts/get"), + params: GetPromptRequestParamsSchema$1 + }); + /** + * Text provided to or from an LLM. + */ + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * An image provided to or from an LLM. + */ + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Audio content provided to or from an LLM. + */ + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A tool call request from an assistant (LLM). + * Represents the assistant's request to use a tool. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * The contents of a resource, embedded into a prompt or tool call result. + */ + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * A resource that the server is capable of reading, included in a prompt or tool call result. + * + * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. + */ + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + /** + * A content block that can be used in prompts and tool results. + */ + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + /** + * Describes a message returned as part of a prompt. + */ + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + /** + * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. + */ + const GetPromptResultSchema$1 = ResultSchema$1.extend({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + /** + * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Additional properties describing a `Tool` to clients. + * + * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. + * They are not guaranteed to provide a faithful description of + * tool behavior (including descriptive properties like `title`). + * + * Clients should never make tool use decisions based on `ToolAnnotations` + * received from untrusted servers. + */ + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + /** + * Execution-related properties for a tool. + */ + const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ + "required", + "optional", + "forbidden" + ]).optional() }); + /** + * Definition for a tool the client can call. + */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()), + outputSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + execution: ToolExecutionSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the client to request a list of tools the server has. + */ + const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); + /** + * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. + */ + const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); + /** + * The server's response to a tool call. + */ + const CallToolResultSchema$1 = ResultSchema$1.extend({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_record(schemas_string(), unknown()).optional(), + isError: schemas_boolean().optional() + }); + /** + * Parameters for a `tools/call` request. + */ + const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Used by the client to invoke a tool provided by the server. + */ + const CallToolRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tools/call"), + params: CallToolRequestParamsSchema$1 + }); + /** + * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. + */ + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * The severity of a log message. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * Parameters for a `logging/setLevel` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); + /** + * A request from the client to the server, to enable or adjust logging. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const SetLevelRequestSchema$1 = RequestSchema$1.extend({ + method: literal("logging/setLevel"), + params: SetLevelRequestParamsSchema$1 + }); + /** + * Parameters for a `notifications/message` notification. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + /** + * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to stderr logging + * (STDIO servers) or OpenTelemetry. + */ + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + /** + * Hints to use for model selection. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + /** + * The server's preferences for model selection, requested of the client during sampling. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + /** + * Controls tool usage behavior in sampling requests. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + /** + * The result of a tool execution, provided by the user (server). + * Represents the outcome of invoking a tool requested via `ToolUseContent`. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), + content: schemas_array(ContentBlockSchema$1), + structuredContent: schemas_object({}).loose().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Basic content types for sampling responses (without tool use). + * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingContentSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1 + ]); + /** + * Content block types allowed in sampling messages. + * This includes text, image, audio, tool use requests, and tool results. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** + * Describes a message issued to or received from an LLM API. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Parameters for a `sampling/createMessage` request. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** + * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request from the server. + * This is the backwards-compatible version that returns single content (no arrays). + * Used when the request does not include tools. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens" + ]).or(schemas_string())), + role: RoleSchema$1, + content: SamplingContentSchema$1 + }); + /** + * The client's response to a `sampling/create_message` request when tools were provided. + * This version supports array content for tool use flows. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to calling LLM + * provider APIs directly. + */ + const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ + model: schemas_string(), + stopReason: schemas_optional(schemas_enum([ + "endTurn", + "stopSequence", + "maxTokens", + "toolUse" + ]).or(schemas_string())), + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) + }); + /** + * Primitive schema definition for boolean fields. + */ + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + /** + * Primitive schema definition for string fields. + */ + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + /** + * Primitive schema definition for number fields. + */ + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + /** + * Schema for single-selection enumeration without display titles for options. + */ + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + /** + * Schema for single-selection enumeration with display titles for each option. + */ + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + /** + * Use {@linkcode TitledSingleSelectEnumSchema} instead. + * This interface will be removed in a future version. + */ + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + /** + * Schema for multiple-selection enumeration without display titles for options. + */ + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Schema for multiple-selection enumeration with display titles for each option. + */ + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + /** + * Combined schema for multiple-selection enumeration + */ + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + /** + * Primitive schema definition for enum fields. + */ + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + /** + * Union of all primitive schema definitions. + */ + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + /** + * Parameters for an `elicitation/create` request for form-based elicitation. + */ + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + /** + * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. + */ + const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("url"), + message: schemas_string(), + elicitationId: schemas_string(), + url: schemas_string().url() + }); + /** + * The parameters for a request to elicit additional information from the user via the client. + */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** + * A request from the server to elicit user input via the client. + * The client should present the message and form fields to the user (form mode) + * or navigate to a URL (URL mode). + */ + const ElicitRequestSchema$1 = RequestSchema$1.extend({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** + * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); + /** + * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. + * + * @category notifications/elicitation/complete + */ + const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/elicitation/complete"), + params: ElicitationCompleteNotificationParamsSchema$1 + }); + /** + * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. + */ + const ElicitResultSchema$1 = ResultSchema$1.extend({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional()) + }); + /** + * A reference to a resource or resource template definition. + */ + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + /** + * Identifies a prompt. + */ + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + /** + * Parameters for a {@linkcode CompleteRequest | completion/complete} request. + */ + const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }); + /** + * A request from the client to the server, to ask for completion options. + */ + const CompleteRequestSchema$1 = RequestSchema$1.extend({ + method: literal("completion/complete"), + params: CompleteRequestParamsSchema$1 + }); + /** + * The server's response to a {@linkcode CompleteRequest | completion/complete} request + */ + const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ + values: schemas_array(schemas_string()).max(100), + total: schemas_optional(schemas_number().int()), + hasMore: schemas_optional(schemas_boolean()) + }) }); + /** + * Represents a root directory or file that the server can operate on. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** + * Sent from the server to request a list of root URIs from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsRequestSchema$1 = RequestSchema$1.extend({ + method: literal("roots/list"), + params: BaseRequestParamsSchema$1.optional() + }); + /** + * The client's response to a `roots/list` request from the server. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); + /** + * A notification from the client to the server, informing it that the list of roots has changed. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains + * in the specification for at least twelve months. Migrate to passing paths via + * tool parameters, resource URIs, or configuration. + */ + const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/roots/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + /** + * Task creation parameters, used to ask that the server create a task to represent a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskCreationParamsSchema$1 = looseObject({ + ttl: schemas_number().optional(), + pollInterval: schemas_number().optional() + }); + /** + * The status of a task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusSchema$1 = schemas_enum([ + "working", + "input_required", + "completed", + "failed", + "cancelled" + ]); + /** + * A pollable state object associated with a request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskSchema$1 = schemas_object({ + taskId: schemas_string(), + status: TaskStatusSchema$1, + ttl: schemas_union([schemas_number(), schemas_null()]), + createdAt: schemas_string(), + lastUpdatedAt: schemas_string(), + pollInterval: schemas_optional(schemas_number()), + statusMessage: schemas_optional(schemas_string()) + }); + /** + * Result returned when a task is created, containing the task data wrapped in a `task` field. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); + /** + * Parameters for task status notification. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); + /** + * A notification sent when a task's status changes. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tasks/status"), + params: TaskStatusNotificationParamsSchema$1 + }); + /** + * A request to get the state of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/get"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a {@linkcode GetTaskRequest | tasks/get} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); + /** + * A request to get the result of a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/result"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + /** + * The response to a `tasks/result` request. + * The structure matches the result type of the original request. + * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. + * + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); + /** + * A request to list tasks. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); + /** + * The response to a {@linkcode ListTasksRequest | tasks/list} request. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); + /** + * A request to cancel a specific task. + * + * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. + */ + const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ + method: literal("tasks/cancel"), + params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) + }); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + RequestSchema: RequestSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + ResultSchema: ResultSchema$1, + RequestIdSchema: RequestIdSchema$1, + EmptyResultSchema: EmptyResultSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, + InitializeRequestSchema: InitializeRequestSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + InitializeResultSchema: InitializeResultSchema$1, + InitializedNotificationSchema: InitializedNotificationSchema$1, + PingRequestSchema: PingRequestSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, + PaginatedRequestSchema: PaginatedRequestSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + RoleSchema: RoleSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, + ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, + SubscribeRequestSchema: SubscribeRequestSchema$1, + UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, + UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolExecutionSchema: ToolExecutionSchema$1, + ToolSchema: ToolSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, + CallToolRequestSchema: CallToolRequestSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, + SetLevelRequestSchema: SetLevelRequestSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingContentSchema: SamplingContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, + ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + RootSchema: RootSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, + TaskCreationParamsSchema: TaskCreationParamsSchema$1, + TaskStatusSchema: TaskStatusSchema$1, + TaskSchema: TaskSchema$1, + CreateTaskResultSchema: CreateTaskResultSchema$1, + TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, + TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, + GetTaskRequestSchema: GetTaskRequestSchema$1, + GetTaskResultSchema: GetTaskResultSchema$1, + GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, + GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, + ListTasksRequestSchema: ListTasksRequestSchema$1, + ListTasksResultSchema: ListTasksResultSchema$1, + CancelTaskRequestSchema: CancelTaskRequestSchema$1, + CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), + ClientRequestSchema: schemas_union([ + PingRequestSchema$1, + InitializeRequestSchema$1, + CompleteRequestSchema$1, + SetLevelRequestSchema$1, + GetPromptRequestSchema$1, + ListPromptsRequestSchema$1, + ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema$1, + SubscribeRequestSchema$1, + UnsubscribeRequestSchema$1, + CallToolRequestSchema$1, + ListToolsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ClientNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + InitializedNotificationSchema$1, + RootsListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1 + ]), + ClientResultSchema: schemas_union([ + EmptyResultSchema$1, + CreateMessageResultSchema$1, + CreateMessageResultWithToolsSchema$1, + ElicitResultSchema$1, + ListRootsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + ServerRequestSchema: schemas_union([ + PingRequestSchema$1, + CreateMessageRequestSchema$1, + ElicitRequestSchema$1, + ListRootsRequestSchema$1, + GetTaskRequestSchema$1, + GetTaskPayloadRequestSchema$1, + ListTasksRequestSchema$1, + CancelTaskRequestSchema$1 + ]), + ServerNotificationSchema: schemas_union([ + CancelledNotificationSchema$1, + ProgressNotificationSchema$1, + LoggingMessageNotificationSchema$1, + ResourceUpdatedNotificationSchema$1, + ResourceListChangedNotificationSchema$1, + ToolListChangedNotificationSchema$1, + PromptListChangedNotificationSchema$1, + TaskStatusNotificationSchema$1, + ElicitationCompleteNotificationSchema$1 + ]), + ServerResultSchema: schemas_union([ + EmptyResultSchema$1, + InitializeResultSchema$1, + CompleteResultSchema$1, + GetPromptResultSchema$1, + ListPromptsResultSchema$1, + ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema$1, + CallToolResultSchema$1, + ListToolsResultSchema$1, + GetTaskResultSchema$1, + ListTasksResultSchema$1, + CreateTaskResultSchema$1 + ]), + CallToolResultWireSchema: unknown().superRefine((value, ctx) => { + if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; + for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { + ctx.addIssue({ + code: "custom", + message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` + }); + return; + } + }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) + }; +} +let memo$1; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2025() { + return memo$1 ??= build$1(); +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts +/** +* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). +* +* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON +* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, +* so when an era-blind handler advertises a non-object root, the 2025 codec's +* `encodeResult('tools/list', …)` projects it down to +* `{type:'object', properties:{result:}, required:['result']}`, and +* `projectCallToolResult` wraps the matching `structuredContent` as +* `{result:}`. The 2026 codec's projections are the identity. +* +* These helpers are wire-layer property — they exist so the projection can +* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} +* and never be re-derived in shared/ or server-side code. +*/ +/** +* Whether a JSON Schema's root is non-object: either an explicit non-object +* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless +* roots that the schema-conversion layer can prove are objects are stamped +* `type:'object'` upstream, so they reach this predicate as object roots. +*/ +function isNonObjectJsonSchemaRoot(json) { + return json["type"] !== "object"; +} +/** +* Keyword-position keys whose values are instance data (not subschemas). A +* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to +* rewrite. Only consulted when the current object is in keyword position — +* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name +* position whose value IS a subschema and is recursed into. +*/ +const REF_REWRITE_DATA_POSITION_KEYS = new Set([ + "const", + "enum", + "default", + "examples" +]); +/** +* Keyword-position keys whose value is a name→subschema map. Entries inside +* such a map are in NAME position: their keys are author-chosen property +* names (which may collide with JSON Schema keywords), their values are +* subschemas to recurse into. +*/ +const REF_REWRITE_NAME_MAP_KEYS = new Set([ + "properties", + "patternProperties", + "$defs", + "definitions", + "dependentSchemas", + "dependencies" +]); +/** +* Whether a subtree's `$id` establishes a new resolution base. A fragment-only +* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not +* change the RFC 3986 base URI — same-document pointers inside still resolve +* against the document root and must be rewritten. +*/ +function establishesNewBase(id) { + return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); +} +/** +* Wrap a non-object output schema in the 2025-era envelope: +* `{type:'object', properties:{result:}, required:['result']}`. +* +* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema +* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) +* are rewritten to account for the new `#/properties/result` root: bare `#` → +* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs +* (anything not starting with `#`) are left untouched. +* +* The rewrite is position-aware: data-valued keywords +* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended +* into; the same names appearing as property names under +* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ +* `dependencies` ARE descended into (they're subschemas). The rewrite is also +* `$id`-scoped: if the natural root carries a base-establishing `$id` no +* pointer is rewritten (same-document refs inside resolve against the embedded +* `$id` base, not the wrapper root), and any subtree that establishes its own +* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, +* draft-07's anchor spelling) does not establish a base and IS descended into. +*/ +function wrapOutputSchemaForLegacy(natural) { + const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; + if (establishesNewBase(natural["$id"])) return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: natural }, + required: ["result"] + }; + const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; + const rewriteRefs = (node, parentIsNameMap) => { + if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); + if (node === null || typeof node !== "object") return node; + if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; + const out = {}; + let convertedRecursion = false; + for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); + else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; + else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; + else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; + else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); + else out[k] = rewriteRefs(v, false); + if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; + else out["$ref"] = "#/properties/result"; + return out; + }; + return { + ...$schema !== void 0 && { $schema }, + type: "object", + properties: { result: rewriteRefs(natural, false) }, + required: ["result"] + }; +} + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/registry.ts +const requestMethodKeys$1 = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "tasks/get": null, + "tasks/result": null, + "tasks/list": null, + "tasks/cancel": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +const notificationMethodKeys$1 = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/initialized": null, + "notifications/roots/list_changed": null, + "notifications/tasks/status": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/elicitation/complete": null +}; +const resultMethodKeys = { + ping: null, + initialize: null, + "completion/complete": null, + "logging/setLevel": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "resources/subscribe": null, + "resources/unsubscribe": null, + "tools/call": null, + "tools/list": null, + "sampling/createMessage": null, + "elicitation/create": null, + "roots/list": null +}; +let maps$1; +function registryMaps() { + if (maps$1) return maps$1; + const s = buildSchemas2025(); + maps$1 = { + requestSchemas: { + ping: s.PingRequestSchema, + initialize: s.InitializeRequestSchema, + "completion/complete": s.CompleteRequestSchema, + "logging/setLevel": s.SetLevelRequestSchema, + "prompts/get": s.GetPromptRequestSchema, + "prompts/list": s.ListPromptsRequestSchema, + "resources/list": s.ListResourcesRequestSchema, + "resources/templates/list": s.ListResourceTemplatesRequestSchema, + "resources/read": s.ReadResourceRequestSchema, + "resources/subscribe": s.SubscribeRequestSchema, + "resources/unsubscribe": s.UnsubscribeRequestSchema, + "tools/call": s.CallToolRequestSchema, + "tools/list": s.ListToolsRequestSchema, + "tasks/get": s.GetTaskRequestSchema, + "tasks/result": s.GetTaskPayloadRequestSchema, + "tasks/list": s.ListTasksRequestSchema, + "tasks/cancel": s.CancelTaskRequestSchema, + "sampling/createMessage": s.CreateMessageRequestSchema, + "elicitation/create": s.ElicitRequestSchema, + "roots/list": s.ListRootsRequestSchema + }, + notificationSchemas: { + "notifications/cancelled": s.CancelledNotificationSchema, + "notifications/progress": s.ProgressNotificationSchema, + "notifications/initialized": s.InitializedNotificationSchema, + "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, + "notifications/tasks/status": s.TaskStatusNotificationSchema, + "notifications/message": s.LoggingMessageNotificationSchema, + "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, + "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, + "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, + "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, + "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema + }, + resultSchemas: { + ping: s.EmptyResultSchema, + initialize: s.InitializeResultSchema, + "completion/complete": s.CompleteResultSchema, + "logging/setLevel": s.EmptyResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "resources/subscribe": s.EmptyResultSchema, + "resources/unsubscribe": s.EmptyResultSchema, + "tools/call": s.CallToolResultWireSchema, + "tools/list": s.ListToolsResultSchema, + "sampling/createMessage": s.CreateMessageResultWithToolsSchema, + "elicitation/create": s.ElicitResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps$1; +} +/** +* Forces the lazy registry maps (and, through them, the era's schema memo). +* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmRegistryMaps2025() { + registryMaps(); +} +/** The 2025-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2025(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); +} +/** The 2025-era notification-method set. */ +function hasNotificationMethod2025(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); +} +/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ +function hasResultMethod(method) { + return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); +} +function getResultSchema(method) { + return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; +} +function getRequestSchema(method) { + return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; +} +function getNotificationSchema(method) { + return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2025RequestMethods = Object.keys(requestMethodKeys$1); +const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); + +//#endregion +//#region ../core-internal/src/wire/rev2025-11-25/codec.ts +function isPlainObject$6(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState$1(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA$1 = { + ok: false, + reason: "not-in-era" +}; +/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ +function toolNeedsLegacyWrap(t) { + return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); +} +/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ +function toNeutralResult(value) { + return value; +} +const rev2025Codec = { + era: "2025-11-25", + hasRequestMethod: hasRequestMethod2025, + hasNotificationMethod: hasNotificationMethod2025, + validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), + validateResult: (method, raw) => triState$1(getResultSchema(method), raw), + validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), + hasInputRequestMethod: () => false, + validateInputRequest: () => NOT_IN_ERA$1, + validateInputResponse: () => NOT_IN_ERA$1, + samplingResultVariant: ((hasTools, raw) => { + const s = buildSchemas2025(); + return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); + }), + outboundEnvelope: (_material) => void 0, + validateEnvelopeMeta: (_meta) => [], + projectCallToolResult(result, advertisedOutputSchema) { + const withText = appendTextFallbackForNonObject(result); + const sc = withText.structuredContent; + if (sc === void 0) return withText; + const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); + const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); + if (!valueIsNonObject && !schemaWrapped) return withText; + return { + ...withText, + structuredContent: { result: sc } + }; + }, + decodeResult(_method, raw) { + if (isPlainObject$6(raw) && "resultType" in raw) { + const stripped = { ...raw }; + delete stripped["resultType"]; + return { + kind: "complete", + result: toNeutralResult(stripped) + }; + } + return { + kind: "complete", + result: toNeutralResult(raw) + }; + }, + encodeResult(method, result) { + if (method !== "tools/list") return result; + const tools = result.tools; + if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; + return { + ...result, + tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { + ...t, + outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) + } : t) + }; + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope: (_material) => void 0 +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts +/** +* 2026-era wire schemas (protocol revision 2026-07-28). +* +* Fully self-contained — no runtime imports from types/schemas.ts. The +* neutral types/schemas.ts layer is the public-API superset and is free to +* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN +* against the 2026-07-28 anchor. Every era-shared building block (content +* blocks, resources, prompts, capabilities, notifications, …) that the wire +* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at +* the point this revision was sealed, dependencies first. The only cross-layer +* dependency is `import type { JSONObject, JSONValue }` from the neutral types +* barrel — pure structural type aliases with no parse behavior. +* +* This module is the only place the per-request `_meta` envelope is modeled. +* The envelope is wire-only vocabulary: the protocol layer lifts it off +* inbound requests before any handler runs and surfaces it at +* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at +* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc +* deferral ("enforced per request at dispatch time, not here") is now +* discharged by that codec step. +* +* No 2025-era traffic ever touches this module, so requiredness here is +* bare and spec-exact (the shared-schema `.catch` hazards do not apply). +* +* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed +* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the +* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from +* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result +* body to the new `ResultMetaObject` key +* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). +* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is +* modeled anywhere (per ruling: the final revision is the only 2026-07-28). +*/ +function build() { + const JSONValueSchema$1 = lazy(() => schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_null(), + schemas_record(schemas_string(), JSONValueSchema$1), + schemas_array(JSONValueSchema$1) + ])); + const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); + /** + * A progress token, used to associate progress notifications with the original request. + */ + const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * An opaque token used to represent a cursor for pagination. + */ + const CursorSchema$1 = schemas_string(); + /** + * A uniquely identifying ID for a request in JSON-RPC. + */ + const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); + /** + * The sender or recipient of messages and data in a conversation. + */ + const RoleSchema$1 = schemas_enum(["user", "assistant"]); + /** + * The severity of a log message. + */ + const LoggingLevelSchema$1 = schemas_enum([ + "debug", + "info", + "notice", + "warning", + "error", + "critical", + "alert", + "emergency" + ]); + /** + * A Zod schema for validating Base64 strings that is more performant and + * robust for very large inputs than the default regex-based check. It avoids + * stack overflows by using the native `atob` function for validation. + */ + const Base64Schema = schemas_string().refine((val) => { + try { + atob(val); + return true; + } catch { + return false; + } + }, { message: "Invalid Base64 string" }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); + const RequestMetaSchema$1 = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() + }); + const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); + const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); + const NotificationSchema$1 = schemas_object({ + method: schemas_string(), + params: NotificationsParamsSchema$1.loose().optional() + }); + const IconSchema$1 = schemas_object({ + src: schemas_string(), + mimeType: schemas_string().optional(), + sizes: schemas_array(schemas_string()).optional(), + theme: schemas_enum(["light", "dark"]).optional() + }); + const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); + const BaseMetadataSchema$1 = schemas_object({ + name: schemas_string(), + title: schemas_string().optional() + }); + const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + version: schemas_string(), + websiteUrl: schemas_string().optional(), + description: schemas_string().optional() + }); + const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); + const ElicitationCapabilitySchema = preprocess((value) => { + if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; + return value; + }, intersection(schemas_object({ + form: FormElicitationCapabilitySchema.optional(), + url: JSONObjectSchema$1.optional() + }), JSONObjectSchema$1.optional())); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ClientTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ + sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), + elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() + }).optional() + }); + /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ + const ServerTasksCapabilitySchema$1 = looseObject({ + list: JSONObjectSchema$1.optional(), + cancel: JSONObjectSchema$1.optional(), + requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() + }); + const ClientCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + sampling: schemas_object({ + context: JSONObjectSchema$1.optional(), + tools: JSONObjectSchema$1.optional() + }).optional(), + elicitation: ElicitationCapabilitySchema.optional(), + roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ClientTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ServerCapabilitiesSchema$1 = schemas_object({ + experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), + logging: JSONObjectSchema$1.optional(), + completions: JSONObjectSchema$1.optional(), + prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + resources: schemas_object({ + subscribe: schemas_boolean().optional(), + listChanged: schemas_boolean().optional() + }).optional(), + tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), + tasks: ServerTasksCapabilitySchema$1.optional(), + extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() + }); + const ProgressSchema$1 = schemas_object({ + progress: schemas_number(), + total: schemas_optional(schemas_number()), + message: schemas_optional(schemas_string()) + }); + const ProgressNotificationParamsSchema$1 = schemas_object({ + ...NotificationsParamsSchema$1.shape, + ...ProgressSchema$1.shape, + progressToken: ProgressTokenSchema$1 + }); + const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/progress"), + params: ProgressNotificationParamsSchema$1 + }); + const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ + level: LoggingLevelSchema$1, + logger: schemas_string().optional(), + data: unknown() + }); + const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/message"), + params: LoggingMessageNotificationParamsSchema$1 + }); + const ResourceContentsSchema$1 = schemas_object({ + uri: schemas_string(), + mimeType: schemas_optional(schemas_string()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); + const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); + const AnnotationsSchema$1 = schemas_object({ + audience: schemas_array(RoleSchema$1).optional(), + priority: schemas_number().min(0).max(1).optional(), + lastModified: iso_datetime({ offset: true }).optional() + }); + const ResourceSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uri: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + size: schemas_optional(schemas_number()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceTemplateSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + uriTemplate: schemas_string(), + description: schemas_optional(schemas_string()), + mimeType: schemas_optional(schemas_string()), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_optional(looseObject({})) + }); + const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); + const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/resources/updated"), + params: ResourceUpdatedNotificationParamsSchema$1 + }); + const PromptArgumentSchema$1 = schemas_object({ + name: schemas_string(), + description: schemas_optional(schemas_string()), + required: schemas_optional(schemas_boolean()) + }); + const PromptSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_optional(schemas_string()), + arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), + _meta: schemas_optional(looseObject({})) + }); + const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/prompts/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const TextContentSchema$1 = schemas_object({ + type: literal("text"), + text: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ImageContentSchema$1 = schemas_object({ + type: literal("image"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const AudioContentSchema$1 = schemas_object({ + type: literal("audio"), + data: Base64Schema, + mimeType: schemas_string(), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ToolUseContentSchema$1 = schemas_object({ + type: literal("tool_use"), + name: schemas_string(), + id: schemas_string(), + input: schemas_record(schemas_string(), unknown()), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const EmbeddedResourceSchema$1 = schemas_object({ + type: literal("resource"), + resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), + annotations: AnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); + const ContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ResourceLinkSchema$1, + EmbeddedResourceSchema$1 + ]); + const PromptMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: ContentBlockSchema$1 + }); + const ToolAnnotationsSchema$1 = schemas_object({ + title: schemas_string().optional(), + readOnlyHint: schemas_boolean().optional(), + destructiveHint: schemas_boolean().optional(), + idempotentHint: schemas_boolean().optional(), + openWorldHint: schemas_boolean().optional() + }); + const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ + method: literal("notifications/tools/list_changed"), + params: NotificationsParamsSchema$1.optional() + }); + const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); + const ModelPreferencesSchema$1 = schemas_object({ + hints: schemas_array(ModelHintSchema$1).optional(), + costPriority: schemas_number().min(0).max(1).optional(), + speedPriority: schemas_number().min(0).max(1).optional(), + intelligencePriority: schemas_number().min(0).max(1).optional() + }); + const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ + "auto", + "required", + "none" + ]).optional() }); + const BooleanSchemaSchema$1 = schemas_object({ + type: literal("boolean"), + title: schemas_string().optional(), + description: schemas_string().optional(), + default: schemas_boolean().optional() + }); + const StringSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minLength: schemas_number().optional(), + maxLength: schemas_number().optional(), + format: schemas_enum([ + "email", + "uri", + "date", + "date-time" + ]).optional(), + default: schemas_string().optional() + }); + const NumberSchemaSchema$1 = schemas_object({ + type: schemas_enum(["number", "integer"]), + title: schemas_string().optional(), + description: schemas_string().optional(), + minimum: schemas_number().optional(), + maximum: schemas_number().optional(), + default: schemas_number().optional() + }); + const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + default: schemas_string().optional() + }); + const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + oneOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })), + default: schemas_string().optional() + }); + const LegacyTitledEnumSchemaSchema$1 = schemas_object({ + type: literal("string"), + title: schemas_string().optional(), + description: schemas_string().optional(), + enum: schemas_array(schemas_string()), + enumNames: schemas_array(schemas_string()).optional(), + default: schemas_string().optional() + }); + const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); + const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ + type: literal("string"), + enum: schemas_array(schemas_string()) + }), + default: schemas_array(schemas_string()).optional() + }); + const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ + type: literal("array"), + title: schemas_string().optional(), + description: schemas_string().optional(), + minItems: schemas_number().optional(), + maxItems: schemas_number().optional(), + items: schemas_object({ anyOf: schemas_array(schemas_object({ + const: schemas_string(), + title: schemas_string() + })) }), + default: schemas_array(schemas_string()).optional() + }); + const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); + const EnumSchemaSchema$1 = schemas_union([ + LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema$1 + ]); + const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ + EnumSchemaSchema$1, + BooleanSchemaSchema$1, + StringSchemaSchema$1, + NumberSchemaSchema$1 + ]); + const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ + mode: literal("form").optional(), + message: schemas_string(), + requestedSchema: schemas_object({ + type: literal("object"), + properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), + required: schemas_array(schemas_string()).optional() + }).catchall(unknown()) + }); + const ResourceTemplateReferenceSchema$1 = schemas_object({ + type: literal("ref/resource"), + uri: schemas_string() + }); + const PromptReferenceSchema$1 = schemas_object({ + type: literal("ref/prompt"), + name: schemas_string() + }); + const RootSchema$1 = schemas_object({ + uri: schemas_string().startsWith("file://"), + name: schemas_string().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; + const ClientCapabilities2026Schema = schemas_object({ + experimental: sharedClientCapabilityShape.experimental, + sampling: sharedClientCapabilityShape.sampling, + elicitation: sharedClientCapabilityShape.elicitation, + roots: sharedClientCapabilityShape.roots, + extensions: sharedClientCapabilityShape.extensions + }); + const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; + const ServerCapabilities2026Schema = schemas_object({ + experimental: sharedServerCapabilityShape.experimental, + logging: sharedServerCapabilityShape.logging, + completions: sharedServerCapabilityShape.completions, + prompts: sharedServerCapabilityShape.prompts, + resources: sharedServerCapabilityShape.resources, + tools: sharedServerCapabilityShape.tools, + extensions: sharedServerCapabilityShape.extensions + }); + /** + * The per-request `_meta` envelope carried by every request under protocol revision + * 2026-07-28: the protocol version governing the request, the client implementation + * info, and the client's capabilities — declared per request rather than once at + * initialization — plus the optional log-level opt-in. + * + * This schema models the complete envelope on its own (loose: foreign keys + * pass through - the lift extracts exactly the reserved keys, so enforcement + * never sees extension material). Requiredness is enforced per request at + * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. + */ + const RequestMetaEnvelopeSchema = looseObject({ + progressToken: ProgressTokenSchema$1.optional(), + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, + [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() + }); + /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ + const ToolSchema$1 = schemas_object({ + ...BaseMetadataSchema$1.shape, + ...IconsSchema$1.shape, + description: schemas_string().optional(), + inputSchema: looseObject({ + $schema: schemas_string().optional(), + type: literal("object") + }), + outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), + annotations: ToolAnnotationsSchema$1.optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ + const ToolResultContentSchema$1 = schemas_object({ + type: literal("tool_result"), + toolUseId: schemas_string(), + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional(), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** 2026-era sampling content union (composes the forked tool-result shape). */ + const SamplingMessageContentBlockSchema$1 = schemas_union([ + TextContentSchema$1, + ImageContentSchema$1, + AudioContentSchema$1, + ToolUseContentSchema$1, + ToolResultContentSchema$1 + ]); + /** 2026-era SamplingMessage (anchor-exact: single block or array). */ + const SamplingMessageSchema$1 = schemas_object({ + role: RoleSchema$1, + content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), + _meta: schemas_record(schemas_string(), unknown()).optional() + }); + /** Open union per the anchor: 'complete' | 'input_required' | string. */ + const ResultTypeSchema = schemas_string(); + /** + * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): + * loose, with the serverInfo key typed when present; the outbound stamp + * is the encode contract's `stampServerInfoMeta` step. + */ + const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); + const wireMeta = ResultMetaSchema.optional(); + function wireResult(shape) { + return looseObject({ + _meta: wireMeta, + resultType: ResultTypeSchema.default("complete"), + ...shape + }); + } + const ResultSchema$1 = wireResult({}); + const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); + const CallToolResultSchema$1 = wireResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }); + const ListToolsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListPromptsResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const GetPromptResultSchema$1 = wireResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }); + const ListResourcesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ListResourceTemplatesResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }); + const ReadResourceResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }); + const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }); + /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ + const CacheableResultSchema = wireResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]) + }); + const DiscoverResultSchema$1 = wireResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }); + /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ + const CreateMessageRequestParamsSchema$1 = schemas_object({ + messages: schemas_array(SamplingMessageSchema$1), + modelPreferences: ModelPreferencesSchema$1.optional(), + systemPrompt: schemas_string().optional(), + includeContext: schemas_enum([ + "none", + "thisServer", + "allServers" + ]).optional(), + temperature: schemas_number().optional(), + maxTokens: schemas_number().int(), + stopSequences: schemas_array(schemas_string()).optional(), + metadata: JSONObjectSchema$1.optional(), + tools: schemas_array(ToolSchema$1).optional(), + toolChoice: ToolChoiceSchema$1.optional() + }); + /** 2026-era embedded sampling request (de-JSON-RPC'd). */ + const CreateMessageRequestSchema$1 = schemas_object({ + method: literal("sampling/createMessage"), + params: CreateMessageRequestParamsSchema$1 + }); + /** + * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input + * requests do NOT carry the per-request `_meta` envelope on this revision — + * the anchor declares a bare optional `_meta` on `params`. + */ + const ListRootsRequestSchema$1 = schemas_object({ + method: literal("roots/list"), + params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() + }); + /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ + const CreateMessageResultSchema$1 = schemas_object({ + ...SamplingMessageSchema$1.shape, + model: schemas_string(), + stopReason: schemas_string().optional() + }); + /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ + const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); + /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ + const ElicitResultSchema$1 = schemas_object({ + action: schemas_enum([ + "accept", + "decline", + "cancel" + ]), + content: schemas_record(schemas_string(), schemas_union([ + schemas_string(), + schemas_number(), + schemas_boolean(), + schemas_array(schemas_string()) + ])).optional() + }); + /** + * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed + * `elicitationId` (and the `notifications/elicitation/complete` channel it + * keyed) — the shared schema keeps the field because it is required on the + * frozen 2025-11-25 revision. + */ + const ElicitRequestURLParamsSchema$1 = schemas_object({ + mode: literal("url"), + message: schemas_string(), + url: schemas_string().url() + }); + /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ + const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); + /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ + const ElicitRequestSchema$1 = schemas_object({ + method: literal("elicitation/create"), + params: ElicitRequestParamsSchema$1 + }); + /** A single embedded input request (one of the three demoted server→client requests). */ + const InputRequestSchema = schemas_union([ + CreateMessageRequestSchema$1, + ListRootsRequestSchema$1, + ElicitRequestSchema$1 + ]); + /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ + const InputResponseSchema = schemas_union([ + CreateMessageResultSchema$1, + ListRootsResultSchema$1, + ElicitResultSchema$1 + ]); + /** Map of embedded input requests, keyed by server-assigned identifiers. */ + const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); + /** Map of embedded input responses, keyed by the corresponding request identifiers. */ + const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); + /** + * The wire InputRequiredResult: `resultType: 'input_required'` plus at least + * one of `inputRequests` / `requestState` (the at-least-one rule is enforced + * at the server seam, not by this parse shape). + */ + const InputRequiredResultSchema = wireResult({ + inputRequests: InputRequestsSchema.optional(), + requestState: schemas_string().optional() + }); + /** The retry-channel members carried by client-initiated requests on this revision. */ + const retryParamsShape = { + inputResponses: InputResponsesSchema.optional(), + requestState: schemas_string().optional() + }; + /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ + const InputResponseRequestParamsSchema = schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...retryParamsShape + }); + /** Post-lift request `_meta` (progressToken + extension keys; loose). */ + const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); + function wireRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: RequestMetaEnvelopeSchema, + ...paramsShape + }) + }); + } + function dispatchRequest(method, paramsShape) { + return schemas_object({ + method: literal(method), + params: schemas_object({ + _meta: DispatchRequestMetaSchema.optional(), + ...paramsShape + }).optional() + }); + } + const callToolParamsShape = { + name: schemas_string(), + arguments: schemas_record(schemas_string(), unknown()).optional(), + ...retryParamsShape + }; + const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; + const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); + const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); + const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); + const GetPromptRequestSchema$1 = wireRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional(), + ...retryParamsShape + }); + const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); + const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); + const ReadResourceRequestSchema$1 = wireRequest("resources/read", { + uri: schemas_string(), + ...retryParamsShape + }); + const completeParamsShape = { + ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), + argument: schemas_object({ + name: schemas_string(), + value: schemas_string() + }), + context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() + }; + const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); + const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); + /** Anchor SubscriptionFilter (2026-only). */ + const SubscriptionFilterSchema$1 = schemas_object({ + toolsListChanged: schemas_boolean().optional(), + promptsListChanged: schemas_boolean().optional(), + resourcesListChanged: schemas_boolean().optional(), + resourceSubscriptions: schemas_array(schemas_string()).optional() + }); + const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; + const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); + /** + * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on + * the graceful-close result. Extends `ResultMetaObject` since spec PR + * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). + */ + const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); + /** + * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` + * response signalling that the subscription has ended gracefully (server + * shutdown). An abrupt transport close carries no response — the client treats + * stream-close-without-result as a disconnect. + */ + const SubscriptionsListenResultSchema$1 = looseObject({ + _meta: SubscriptionsListenResultMetaSchema$1, + resultType: ResultTypeSchema.default("complete") + }); + /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ + const dispatchRequestSchemas = { + "tools/call": dispatchRequest("tools/call", callToolParamsShape), + "tools/list": dispatchRequest("tools/list", paginatedParamsShape), + "prompts/get": dispatchRequest("prompts/get", { + name: schemas_string(), + arguments: schemas_record(schemas_string(), schemas_string()).optional() + }), + "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), + "resources/list": dispatchRequest("resources/list", paginatedParamsShape), + "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), + "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), + "completion/complete": dispatchRequest("completion/complete", completeParamsShape), + "server/discover": dispatchRequest("server/discover", {}), + "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) + }; + /** Dispatch (post-lift) result schemas, keyed by method — what the funnel + * validates AFTER `decodeResult` consumed `resultType`. */ + function liftedResult(shape) { + return looseObject({ + _meta: wireMeta, + ...shape + }); + } + const dispatchResultSchemas = { + "tools/call": liftedResult({ + content: schemas_array(ContentBlockSchema$1), + structuredContent: unknown().optional(), + isError: schemas_boolean().optional() + }), + "tools/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + tools: schemas_array(ToolSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "prompts/get": liftedResult({ + description: schemas_string().optional(), + messages: schemas_array(PromptMessageSchema$1) + }), + "prompts/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + prompts: schemas_array(PromptSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resources: schemas_array(ResourceSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/templates/list": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + resourceTemplates: schemas_array(ResourceTemplateSchema$1), + nextCursor: CursorSchema$1.optional() + }), + "resources/read": liftedResult({ + ttlMs: schemas_number().int().min(0), + cacheScope: schemas_enum(["public", "private"]), + contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) + }), + "completion/complete": liftedResult({ completion: schemas_object({ + values: schemas_array(schemas_string()).max(100), + total: schemas_number().int().optional(), + hasMore: schemas_boolean().optional() + }).loose() }), + "server/discover": liftedResult({ + ttlMs: schemas_number().int().min(0).catch(0), + cacheScope: schemas_enum(["public", "private"]).catch("private"), + supportedVersions: schemas_array(schemas_string()), + capabilities: ServerCapabilities2026Schema, + instructions: schemas_string().optional() + }), + "subscriptions/listen": liftedResult({}) + }; + /** + * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the + * subscriptions/listen demux key typed when present. Only the anchor-exact + * SHAPE is modeled here — listen delivery itself (filter gating, demux, + * teardown) is #14 scope and not implemented by this module. + */ + const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); + /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ + const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ + method: literal("notifications/subscriptions/acknowledged"), + params: schemas_object({ + _meta: NotificationMetaSchema.optional(), + notifications: SubscriptionFilterSchema$1 + }) + }); + /** + * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` + * is REQUIRED on this revision — the shared schema keeps it optional because + * the frozen 2025-11-25 shape declares it optional (task cancellation goes + * through `tasks/cancel` there). Requiredness is bare because no 2025-era + * traffic touches this module. + */ + const CancelledNotificationParamsSchema$1 = schemas_object({ + _meta: NotificationMetaSchema.optional(), + requestId: RequestIdSchema$1, + reason: schemas_string().optional() + }); + /** 2026-era `notifications/cancelled` (see the params fork above). */ + const CancelledNotificationSchema$1 = schemas_object({ + method: literal("notifications/cancelled"), + params: CancelledNotificationParamsSchema$1 + }); + const notificationSchemas2026 = { + "notifications/cancelled": CancelledNotificationSchema$1, + "notifications/progress": ProgressNotificationSchema$1, + "notifications/message": LoggingMessageNotificationSchema$1, + "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, + "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, + "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, + "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, + "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 + }; + const wireResultResponse = (result) => schemas_object({ + jsonrpc: literal("2.0"), + id: schemas_union([schemas_string(), schemas_number().int()]), + result + }).strict(); + return { + JSONValueSchema: JSONValueSchema$1, + JSONObjectSchema: JSONObjectSchema$1, + ProgressTokenSchema: ProgressTokenSchema$1, + CursorSchema: CursorSchema$1, + RequestIdSchema: RequestIdSchema$1, + RoleSchema: RoleSchema$1, + LoggingLevelSchema: LoggingLevelSchema$1, + TaskMetadataSchema: TaskMetadataSchema$1, + RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, + RequestMetaSchema: RequestMetaSchema$1, + BaseRequestParamsSchema: BaseRequestParamsSchema$1, + TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, + NotificationsParamsSchema: NotificationsParamsSchema$1, + NotificationSchema: NotificationSchema$1, + IconSchema: IconSchema$1, + IconsSchema: IconsSchema$1, + BaseMetadataSchema: BaseMetadataSchema$1, + ImplementationSchema: ImplementationSchema$1, + ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, + ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, + ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, + ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, + ProgressSchema: ProgressSchema$1, + ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, + ProgressNotificationSchema: ProgressNotificationSchema$1, + LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, + LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, + ResourceContentsSchema: ResourceContentsSchema$1, + TextResourceContentsSchema: TextResourceContentsSchema$1, + BlobResourceContentsSchema: BlobResourceContentsSchema$1, + AnnotationsSchema: AnnotationsSchema$1, + ResourceSchema: ResourceSchema$1, + ResourceTemplateSchema: ResourceTemplateSchema$1, + ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, + ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, + ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, + PromptArgumentSchema: PromptArgumentSchema$1, + PromptSchema: PromptSchema$1, + PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, + TextContentSchema: TextContentSchema$1, + ImageContentSchema: ImageContentSchema$1, + AudioContentSchema: AudioContentSchema$1, + ToolUseContentSchema: ToolUseContentSchema$1, + EmbeddedResourceSchema: EmbeddedResourceSchema$1, + ResourceLinkSchema: ResourceLinkSchema$1, + ContentBlockSchema: ContentBlockSchema$1, + PromptMessageSchema: PromptMessageSchema$1, + ToolAnnotationsSchema: ToolAnnotationsSchema$1, + ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, + ModelHintSchema: ModelHintSchema$1, + ModelPreferencesSchema: ModelPreferencesSchema$1, + ToolChoiceSchema: ToolChoiceSchema$1, + BooleanSchemaSchema: BooleanSchemaSchema$1, + StringSchemaSchema: StringSchemaSchema$1, + NumberSchemaSchema: NumberSchemaSchema$1, + UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, + TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, + LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, + SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, + UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, + TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, + MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, + EnumSchemaSchema: EnumSchemaSchema$1, + PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, + ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, + ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, + PromptReferenceSchema: PromptReferenceSchema$1, + RootSchema: RootSchema$1, + ClientCapabilities2026Schema, + ServerCapabilities2026Schema, + RequestMetaEnvelopeSchema, + ToolSchema: ToolSchema$1, + ToolResultContentSchema: ToolResultContentSchema$1, + SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, + SamplingMessageSchema: SamplingMessageSchema$1, + ResultTypeSchema, + ResultMetaSchema, + ResultSchema: ResultSchema$1, + PaginatedResultSchema: PaginatedResultSchema$1, + CallToolResultSchema: CallToolResultSchema$1, + ListToolsResultSchema: ListToolsResultSchema$1, + ListPromptsResultSchema: ListPromptsResultSchema$1, + GetPromptResultSchema: GetPromptResultSchema$1, + ListResourcesResultSchema: ListResourcesResultSchema$1, + ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, + ReadResourceResultSchema: ReadResourceResultSchema$1, + CompleteResultSchema: CompleteResultSchema$1, + CacheableResultSchema, + DiscoverResultSchema: DiscoverResultSchema$1, + CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, + CreateMessageRequestSchema: CreateMessageRequestSchema$1, + ListRootsRequestSchema: ListRootsRequestSchema$1, + CreateMessageResultSchema: CreateMessageResultSchema$1, + ListRootsResultSchema: ListRootsResultSchema$1, + ElicitResultSchema: ElicitResultSchema$1, + ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, + ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, + ElicitRequestSchema: ElicitRequestSchema$1, + InputRequestSchema, + InputResponseSchema, + InputRequestsSchema, + InputResponsesSchema, + InputRequiredResultSchema, + InputResponseRequestParamsSchema, + CallToolRequestSchema: CallToolRequestSchema$1, + ListToolsRequestSchema: ListToolsRequestSchema$1, + ListPromptsRequestSchema: ListPromptsRequestSchema$1, + GetPromptRequestSchema: GetPromptRequestSchema$1, + ListResourcesRequestSchema: ListResourcesRequestSchema$1, + ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, + ReadResourceRequestSchema: ReadResourceRequestSchema$1, + CompleteRequestSchema: CompleteRequestSchema$1, + DiscoverRequestSchema: DiscoverRequestSchema$1, + SubscriptionFilterSchema: SubscriptionFilterSchema$1, + SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, + SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, + SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, + dispatchRequestSchemas, + dispatchResultSchemas, + NotificationMetaSchema, + SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, + CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, + CancelledNotificationSchema: CancelledNotificationSchema$1, + notificationSchemas2026, + JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), + CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), + ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), + ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), + GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), + ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), + ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), + ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), + CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), + DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) + }; +} +let src_CX2iR2pK_memo; +/** +* Builds the era wire-schema set on first call and returns the same object +* thereafter. Module evaluation stays construction-free so importing the +* era codec/registry costs nothing until the first validation actually +* needs a schema; the registry, the codec, and the eager `schemas.ts` +* shim all pull through this memo, so reference identity holds across +* every consumer. +*/ +function buildSchemas2026() { + return src_CX2iR2pK_memo ??= build(); +} + +//#endregion +//#region ../core-internal/src/shared/resultCacheHints.ts +/** +* The operations whose results are cacheable on the 2026-07-28 revision (the +* `CacheableResult` extenders). This list is closed: no other operation's +* result ever receives cache fields from the SDK. +*/ +const CACHEABLE_RESULT_METHODS = [ + "tools/list", + "prompts/list", + "resources/list", + "resources/templates/list", + "resources/read", + "server/discover" +]; +/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ +function isCacheableResultMethod(method) { + return CACHEABLE_RESULT_METHODS.includes(method); +} +/** +* The symbol-keyed carrier for a configured cache hint on a result object. +* Symbol properties are invisible to JSON serialization, so the carrier can be +* attached era-blind: only the 2026-era encode seam consumes it. +*/ +const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); +/** +* Attaches a configured cache hint to a result as the encode-time fallback. +* Returns the result unchanged when there is nothing to attach. When a more +* specific hint is already attached, the two hints are combined per field +* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the +* per-registration hint attached by the feature layer keeps every field it +* sets, and the server-level per-operation hint only fills the fields the +* more specific hint leaves unset. +*/ +function attachCacheHintFallback(result, hint) { + if (hint === void 0) return result; + const attached = result[RESULT_CACHE_HINT_FALLBACK]; + if (attached === void 0) return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: hint + }; + const merged = {}; + const ttlMs = attached.ttlMs ?? hint.ttlMs; + if (ttlMs !== void 0) merged.ttlMs = ttlMs; + const cacheScope = attached.cacheScope ?? hint.cacheScope; + if (cacheScope !== void 0) merged.cacheScope = cacheScope; + return { + ...result, + [RESULT_CACHE_HINT_FALLBACK]: merged + }; +} +/** Reads the configured cache-hint fallback attached to a result, if any. */ +function cacheHintFallbackOf(result) { + return result[RESULT_CACHE_HINT_FALLBACK]; +} +/** +* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe +* integers are required because the wire schemas validate `ttlMs` as an +* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value +* outside that range is treated as invalid here so it falls through to the +* next author instead of being emitted and rejected downstream. +*/ +function isValidCacheTtlMs(value) { + return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; +} +/** Whether a value is a valid `cacheScope`. */ +function isValidCacheScope(value) { + return value === "public" || value === "private"; +} +/** +* Validates a configured cache hint at configuration time. Throws a +* `RangeError` naming the offending field, so misconfiguration fails at +* startup/registration rather than silently degrading at encode time. +*/ +function assertValidCacheHint(hint, context) { + if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); + if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); +} + +//#endregion +//#region ../core-internal/src/types/enums.ts +/** +* Error codes for protocol errors that cross the wire as JSON-RPC error responses. +* These follow the JSON-RPC specification and MCP-specific extensions. +*/ +let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { + ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; + ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; + ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; + /** + * Resource not found. + * + * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` + * misses answer `-32602` (Invalid Params) on every protocol revision per + * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to + * `-32602` at the era encode seam. The member stays importable so clients + * can recognise `-32002` from peers built on earlier SDK releases (the + * spec's "clients SHOULD also accept `-32002`" backwards-compatibility + * clause). Throw `ResourceNotFoundError` instead. + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; + /** + * Processing the request requires a capability the client did not declare + * in the request's `clientCapabilities` (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; + /** + * The request's protocol version is unknown to the server or unsupported + * by it (protocol revision 2026-07-28). + */ + ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; + ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; + return ProtocolErrorCode$1; +}({}); + +//#endregion +//#region ../core-internal/src/types/errors.ts +/** +* Protocol errors are JSON-RPC errors that cross the wire as error responses. +* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. +* +* `instanceof` on this class (and its subclasses) is brand-matched, so it works +* across separately bundled copies of the SDK — e.g. an error constructed by +* `@modelcontextprotocol/client` matches the class re-exported by +* `@modelcontextprotocol/server` in the same process. +*/ +var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); + } + static [Symbol.hasInstance](value) { + return brandedHasInstance(this, value); + } + /** + * Brand-based type guard: equivalent to `value instanceof this`, as an + * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads + * the caller's own brand via `this`, so every branded subclass gets a + * correctly-scoped guard by inheritance. Must be invoked on the class — + * in callback position write `v => SdkError.isInstance(v)`, not + * `.filter(SdkError.isInstance)` (detached calls throw rather than + * silently matching nothing). + */ + static isInstance(value) { + if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); + return brandedHasInstance(this, value); + } + constructor(code, message, data) { + super(message); + this.code = code; + this.data = data; + this.name = "ProtocolError"; + stampErrorBrands(this, new.target); + } + /** + * Factory method to create the appropriate error type based on the error code and data + */ + static fromError(code, message, data) { + if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { + const errorData = data; + if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { + const errorData = data; + if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: errorData.supported, + requested: errorData.requested + }, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { + const errorData = data; + if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); + } + if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { + const errorData = data; + if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); + } + return new ProtocolError(code, message, data); + } +}; +/** +* Error type for a `resources/read` miss: the requested resource does not +* exist. The wire code is `-32602` (Invalid Params) on every protocol +* revision — the spec MUST for revision 2026-07-28, and the value the v1.x +* SDK has always emitted on earlier revisions. The error data echoes the +* requested URI. +* +* Recognise this error by checking `error.data` is exactly `{ uri: string }` +* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; +* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also +* accept `-32002` as resource not found — earlier SDK builds emitted that +* code, and {@linkcode ProtocolError.fromError} reconstructs this class for +* either code **when `error.data` carries `uri`** (a bare `-32002` without +* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks +* are brand-matched and work across separately bundled copies of the SDK. +*/ +var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); + } + constructor(uri, message = `Resource not found: ${uri}`) { + super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); + } + /** The URI that was requested and not found. */ + get uri() { + return this.data.uri; + } +}; +/** +* Specialized error type when a tool requires a URL mode elicitation. +* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. +*/ +var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); + } + constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { + super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); + } + get elicitations() { + return this.data?.elicitations ?? []; + } +}; +/** +* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol +* revision 2026-07-28): the request's protocol version is unknown to the server or +* unsupported by it. +* +* The error data lists the protocol versions the receiver supports (`supported`), +* so the sender can choose a mutually supported version and retry, and echoes the +* version that was requested (`requested`). +*/ +var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); + } + constructor(data, message = `Unsupported protocol version: ${data.requested}`) { + super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); + } + /** + * Protocol versions the receiver supports. + */ + get supported() { + return this.data.supported; + } + /** + * The protocol version that was requested. + */ + get requested() { + return this.data.requested; + } +}; +/** +* Error type for the `-32021` MissingRequiredClientCapability protocol error +* (protocol revision 2026-07-28): processing the request requires a capability +* the client did not declare in the request's `clientCapabilities`. +* +* The error data lists the missing capabilities (`requiredCapabilities`) in +* the `ClientCapabilities` shape, so the client can see exactly what it would +* have to declare for the request to be served. On HTTP, the response status +* is `400 Bad Request`. +* +* Recognize this error by its code and `data.requiredCapabilities`, or by +* `instanceof` — checks are brand-matched and work across separately bundled +* copies of the SDK. +*/ +var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { + static { + Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); + } + constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { + super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); + } + /** + * The capabilities the server requires from the client to process the + * request (only the missing capabilities are listed). + */ + get requiredCapabilities() { + return this.data.requiredCapabilities; + } +}; + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts +/** The default cache policy when neither the handler nor configuration provides one. */ +const DEFAULT_CACHE_TTL_MS = 0; +const DEFAULT_CACHE_SCOPE = "private"; +/** +* Request methods whose spec result vocabulary goes beyond `'complete'` on the +* 2026-07-28 revision: their results may be `input_required` (multi +* round-trip requests), so a handler-provided `resultType` passes through the +* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits +* a JSON-RPC result — termination is stream close (HTTP) or +* `notifications/cancelled` (stdio) per the spec. +*/ +const EXTENDED_RESULT_TYPE_METHODS = [ + "tools/call", + "prompts/get", + "resources/read" +]; +/** +* Step 1 of the encode contract: ensure the outbound result carries the +* required `resultType` discriminator. +* +* - No handler-provided value → stamp `'complete'`. +* - Handler-provided `'complete'` → kept as-is. +* - Handler-provided non-`'complete'` value on a method whose vocabulary +* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. +* The value is forwarded verbatim — the wire vocabulary is an open union and +* the SDK does not validate the string, so emitting a `resultType` the +* negotiated revision does not define is the handler author's +* responsibility. +* - Handler-provided non-`'complete'` value on any other method → internal +* error (loud): the value would be mis-typed on the wire, and silently +* rewriting it would hide a server bug. +*/ +function stampResultType(method, result) { + const provided = result["resultType"]; + if (provided === void 0) return { + ...result, + resultType: "complete" + }; + if (provided === "complete") return result; + if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); +} +/** +* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields +* on cacheable results. +* +* Applies only when the (post-stamp) `resultType` is `'complete'` and the +* method is one of the cacheable operations; everything else is returned +* untouched apart from removing the configured-hint carrier. Field resolution +* is per field, most specific author first: a valid handler-returned value, +* then the configured cache hint attached by the server layer, then the +* defaults. Handler-returned values are validated at encode time (`ttlMs` +* must be a non-negative integer, `cacheScope` must be `'public'` or +* `'private'`); invalid values are ignored rather than emitted. +*/ +function fillCacheFields(method, result) { + const fallback = cacheHintFallbackOf(result); + if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); + const provided = result; + const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); + const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); + const filled = { + ...provided, + ttlMs, + cacheScope + }; + delete filled[RESULT_CACHE_HINT_FALLBACK]; + return filled; +} +function isPlainObject$5(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** +* Step 3 of the encode contract: stamp the server's identity into the +* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: +* servers SHOULD include it on every response). +* +* - No `serverInfo` supplied (a client instance, or a hand-constructed +* protocol object) → identity function. +* - The result's `_meta` already carries the key → kept as-is (the handler +* is the more specific author; mirrors the cache-fill resolution order). +* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: +* the stamp never rewrites handler material, and the malformed value fails +* loudly at the peer instead of being silently replaced here. +* - Otherwise → the key is added, preserving any other `_meta` entries. +* +* Runs for every result regardless of `resultType`: the anchor types +* `Result._meta` as `ResultMetaObject` on all results, `input_required` +* included. +*/ +function stampServerInfoMeta(result, serverInfo) { + if (serverInfo === void 0) return result; + const meta = result["_meta"]; + if (meta === void 0) return { + ...result, + _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } + }; + if (!isPlainObject$5(meta)) return result; + if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; + return { + ...result, + _meta: { + ...meta, + [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo + } + }; +} +function resolveTtlMs(fallback) { + return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; +} +function resolveCacheScope(fallback) { + return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; +} +function stripCacheHintFallback(result) { + const copy = { ...result }; + delete copy[RESULT_CACHE_HINT_FALLBACK]; + return copy; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts +/** +* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 +* multi round-trip requests), dispatch view. +* +* The three former server→client wire requests (`elicitation/create`, +* `sampling/createMessage`, `roots/list`) are NOT wire request methods on +* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an +* `input_required` result. The multi-round-trip driver dispatches those +* embedded payloads to the client's registered handlers through the normal +* handler machinery, and these are the schemas that dispatch parses them +* with: lenient where the anchor's wire-true artifacts are strict (an +* embedded request never carries the per-request `_meta` envelope), exact +* where the vocabulary forks (the sampling shapes compose the forked +* SamplingMessage/Tool payloads). +* +* Registry membership is intentionally NOT granted here — these methods stay +* absent from the 2026-era request registry (a peer sending one as a wire +* request still gets −32601 by absence). Only the codec's +* `inputRequestSchema`/`inputResponseSchema` accessors expose them. +*/ +/** The embedded input-request methods of the 2026-07-28 revision. */ +const INPUT_REQUEST_METHODS_2026 = [ + "elicitation/create", + "sampling/createMessage", + "roots/list" +]; +let maps; +function inputSchemaMaps() { + if (maps) return maps; + const s = buildSchemas2026(); + maps = { + request: { + "elicitation/create": schemas_object({ + method: literal("elicitation/create"), + params: s.ElicitRequestParamsSchema + }), + "sampling/createMessage": schemas_object({ + method: literal("sampling/createMessage"), + params: s.CreateMessageRequestParamsSchema + }), + "roots/list": schemas_object({ + method: literal("roots/list"), + params: looseObject({}).optional() + }) + }, + response: { + "elicitation/create": s.ElicitResultSchema, + "sampling/createMessage": s.CreateMessageResultSchema, + "roots/list": s.ListRootsResultSchema + } + }; + return maps; +} +/** +* Forces the lazy embedded-request maps (and, through them, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. +*/ +function warmInputSchemaMaps2026() { + inputSchemaMaps(); +} +function isInputRequestMethod2026(method) { + return INPUT_REQUEST_METHODS_2026.includes(method); +} +function getInputRequestSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; +} +function getInputResponseSchema2026(method) { + return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; +} + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/registry.ts +const requestMethodKeys = { + "tools/call": null, + "tools/list": null, + "prompts/get": null, + "prompts/list": null, + "resources/list": null, + "resources/templates/list": null, + "resources/read": null, + "completion/complete": null, + "server/discover": null, + "subscriptions/listen": null +}; +const notificationMethodKeys = { + "notifications/cancelled": null, + "notifications/progress": null, + "notifications/message": null, + "notifications/resources/updated": null, + "notifications/resources/list_changed": null, + "notifications/tools/list_changed": null, + "notifications/prompts/list_changed": null, + "notifications/subscriptions/acknowledged": null +}; +/** The 2026-era request-method set (registry membership = the deletion story). */ +function hasRequestMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +/** The 2026-era notification-method set. */ +function hasNotificationMethod2026(method) { + return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); +} +/** Result-map membership (same key set as the request map on this era). */ +function hasResultMethod2026(method) { + return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); +} +function getRequestSchema2026(method) { + return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; +} +function getResultSchema2026(method) { + return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; +} +function getNotificationSchema2026(method) { + return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; +} +/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ +const rev2026RequestMethods = Object.keys(requestMethodKeys); +const rev2026NotificationMethods = Object.keys(notificationMethodKeys); + +//#endregion +//#region ../core-internal/src/wire/rev2026-07-28/codec.ts +function isPlainObject$4(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ +function triState(schema, raw) { + if (schema === void 0) return { + ok: false, + reason: "not-in-era" + }; + const parsed = schema.safeParse(raw); + return parsed.success ? { + ok: true, + value: parsed.data + } : { + ok: false, + reason: "invalid", + message: String(parsed.error) + }; +} +const NOT_IN_ERA = { + ok: false, + reason: "not-in-era" +}; +/** +* The reserved `_meta` keys an envelope must carry on this era (in reporting +* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a +* request without it is accepted (a present-but-malformed value still fails +* the envelope schema parse below). +*/ +const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; +/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ +function enforceDeletedFields(method, result) { + let next = result; + let copied = false; + const copy = () => { + if (!copied) { + next = { ...next }; + copied = true; + } + return next; + }; + const tools = result.tools; + if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { + if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; + const rest = { ...tool }; + delete rest["execution"]; + return rest; + }); + const capabilities = result.capabilities; + if (isPlainObject$4(capabilities) && "tasks" in capabilities) { + const rest = { ...capabilities }; + delete rest["tasks"]; + copy().capabilities = rest; + } + return next; +} +const rev2026Codec = { + era: "2026-07-28", + hasRequestMethod: hasRequestMethod2026, + hasNotificationMethod: hasNotificationMethod2026, + hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, + validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), + validateResult: (method, raw) => triState(getResultSchema2026(method), raw), + validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), + validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), + validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), + samplingResultVariant: () => NOT_IN_ERA, + outboundEnvelope(material) { + return { + [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, + [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, + [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, + ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } + }; + }, + validateEnvelopeMeta(meta) { + const issues = []; + for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ + key, + problem: "missing" + }); + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); + if (!parsed.success) for (const issue of parsed.error.issues) { + const path = issue.path.map(String); + const key = path.length > 0 ? path.join(".") : "_meta"; + if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; + issues.push({ + key, + problem: issue.message + }); + } + return issues; + }, + projectCallToolResult: (result) => appendTextFallbackForNonObject(result), + inputRequestSchema: getInputRequestSchema2026, + decodeResult(method, raw) { + if (!isPlainObject$4(raw)) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) + }; + const rawResultType = raw["resultType"]; + if (rawResultType === void 0) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { + method, + violation: "missing-resultType" + }) + }; + if (typeof rawResultType !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { + method, + resultType: rawResultType + }) + }; + if (rawResultType === "input_required") { + const rawInputRequests = raw["inputRequests"]; + const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; + const requestState = raw["requestState"]; + if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { + method, + violation: "input-required-missing-both" + }) + }; + return { + kind: "input_required", + inputRequests, + ...typeof requestState === "string" && { requestState } + }; + } + if (rawResultType !== "complete") return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { + resultType: rawResultType, + method + }) + }; + const wireResultSchemas = getWireResultSchemas(); + const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; + if (wireSchema !== void 0) { + const parsed = wireSchema.safeParse(raw); + if (!parsed.success) return { + kind: "invalid", + error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) + }; + } + const lifted = { ...raw }; + delete lifted["resultType"]; + return { + kind: "complete", + result: lifted + }; + }, + encodeResult(method, result, serverInfo) { + return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); + }, + encodeErrorCode: (code) => code === -32002 ? -32602 : code, + checkInboundEnvelope(material) { + if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; + const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); + if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; + } +}; +/** Wire-true result wrappers consulted by decode step 2, keyed by method — +* built once through the era's schema memo on the first decode. */ +let wireResultSchemasMemo; +function getWireResultSchemas() { + if (wireResultSchemasMemo) return wireResultSchemasMemo; + const s = buildSchemas2026(); + wireResultSchemasMemo = { + "tools/call": s.CallToolResultSchema, + "tools/list": s.ListToolsResultSchema, + "prompts/get": s.GetPromptResultSchema, + "prompts/list": s.ListPromptsResultSchema, + "resources/list": s.ListResourcesResultSchema, + "resources/templates/list": s.ListResourceTemplatesResultSchema, + "resources/read": s.ReadResourceResultSchema, + "completion/complete": s.CompleteResultSchema, + "server/discover": s.DiscoverResultSchema + }; + return wireResultSchemasMemo; +} +/** +* Forces the lazy wire-result wrapper map (and, through it, the era's schema +* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. +*/ +function warmWireResultSchemas2026() { + getWireResultSchemas(); +} + +//#endregion +//#region ../core-internal/src/wire/codec.ts +/** +* The modern wire revision literal. Internal only — deliberately NOT a public +* constant (G-D2-4: no public modern-version constant ships before era-aware +* list semantics exist). +*/ +const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; +/** +* Era resolution, many-to-one (Q1-SD1): every modern-era revision +* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five +* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era +* codec (the DV-13 default posture — hand-constructed instances and +* unclassified traffic are legacy-era). This is the same era predicate the +* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern +* revision other than the literal '2026-07-28' must still resolve modern. +*/ +function src_CX2iR2pK_codecForVersion(version) { + return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; +} +/** +* The wire era an edge classification names (Q2 — produced at the +* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no +* longer resolves a codec FROM the classification: era is instance state, and +* a classified inbound message is VALIDATED against the instance era — a +* mismatch is an entry/routing error, never a per-message era switch. The +* exact `revision` wins over the coarse era flag when both are present. +*/ +function classifiedWireEra(classification) { + if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; + return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; +} +/** +* The derived spec-method universe: the union of every codec registry. A +* method in this set is era-gated at dispatch and send time; a method outside +* it is a consumer-owned extension method (era-blind, schema-explicit). +* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS +* table class is exactly what registry membership replaces). +*/ +function isSpecRequestMethod(method) { + return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); +} +function isSpecNotificationMethod(method) { + return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); +} +const ALL_CODECS = [rev2025Codec, rev2026Codec]; + +//#endregion +//#region ../core-internal/src/shared/envelope.ts +/** +* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). +* +* Pure, value-returning helpers used by the inbound HTTP classifier +* (`classifyInboundRequest`): claim detection and envelope validation with +* self-identifying issues. The envelope schema itself stays the wire layer's +* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps +* its outcomes into the shapes the validation ladder emits. +* +* Claim detection is deliberately narrow: a message claims the 2026-07-28 +* envelope mechanism if and only if the reserved protocol-version `_meta` key +* is present in `params._meta`. Other reserved keys (client info, client +* capabilities, log level), a bare `progressToken`, or unrelated keys under +* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their +* own — but once the claim key is present, a malformed envelope is a +* validation error, never a silent fall back to legacy handling. +* +* The wire-exact envelope schema, the required-key set, and the per-key issue +* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). +* This module never reaches into a per-revision wire module directly. +*/ +function isPlainObject$3(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +/** The `_meta` object of a message's params, when present. */ +function src_CX2iR2pK_requestMetaOf(params) { + if (!isPlainObject$3(params)) return void 0; + const meta = params["_meta"]; + return isPlainObject$3(meta) ? meta : void 0; +} +/** +* Whether a message's params carry the per-request envelope claim: the +* reserved protocol-version `_meta` key is present (regardless of whether the +* rest of the envelope is valid — validation is a separate, later step). +*/ +function src_CX2iR2pK_hasEnvelopeClaim(params) { + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; +} +/** +* The protocol version named by a message's envelope claim, when the claim is +* present and carries a string value. A present claim with a non-string value +* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a +* validation issue instead of a version. +*/ +function src_CX2iR2pK_envelopeClaimVersion(params) { + const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; + return typeof value === "string" ? value : void 0; +} +/** +* Validates a request's `_meta` object as a 2026-07-28 per-request envelope +* and reports problems as self-identifying issues (which key, what problem). +* +* Returns an empty array when the envelope is valid. Missing required keys are +* reported first (as `problem: 'missing'`), then schema violations inside +* present keys, in a stable order. +*/ +function src_CX2iR2pK_validateEnvelopeMeta(meta) { + return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); +} + +//#endregion +//#region ../core-internal/src/types/schemas.ts +var schemas_exports = /* @__PURE__ */ __exportAll({ + AnnotationsSchema: () => AnnotationsSchema, + AudioContentSchema: () => AudioContentSchema, + BaseMetadataSchema: () => BaseMetadataSchema, + BaseRequestParamsSchema: () => BaseRequestParamsSchema, + BlobResourceContentsSchema: () => BlobResourceContentsSchema, + BooleanSchemaSchema: () => BooleanSchemaSchema, + CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, + CallToolRequestSchema: () => CallToolRequestSchema, + CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, + CancelTaskRequestSchema: () => CancelTaskRequestSchema, + CancelTaskResultSchema: () => CancelTaskResultSchema, + CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, + CancelledNotificationSchema: () => CancelledNotificationSchema, + ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, + ClientNotificationSchema: () => ClientNotificationSchema, + ClientRequestSchema: () => ClientRequestSchema, + ClientResultSchema: () => ClientResultSchema, + ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, + CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, + CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, + CompleteRequestSchema: () => CompleteRequestSchema, + CompleteResultSchema: () => CompleteResultSchema, + ContentBlockSchema: () => ContentBlockSchema, + CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, + CreateMessageRequestSchema: () => CreateMessageRequestSchema, + CreateMessageResultSchema: () => CreateMessageResultSchema, + CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, + CreateTaskResultSchema: () => CreateTaskResultSchema, + CursorSchema: () => CursorSchema, + DiscoverRequestSchema: () => DiscoverRequestSchema, + DiscoverResultSchema: () => DiscoverResultSchema, + ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, + ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, + ElicitRequestSchema: () => ElicitRequestSchema, + ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, + ElicitResultSchema: () => ElicitResultSchema, + ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, + ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, + EmbeddedResourceSchema: () => EmbeddedResourceSchema, + EmptyResultSchema: () => EmptyResultSchema, + EnumSchemaSchema: () => EnumSchemaSchema, + GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, + GetPromptRequestSchema: () => GetPromptRequestSchema, + GetPromptResultSchema: () => GetPromptResultSchema, + GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, + GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, + GetTaskRequestSchema: () => GetTaskRequestSchema, + GetTaskResultSchema: () => GetTaskResultSchema, + IconSchema: () => IconSchema, + IconsSchema: () => IconsSchema, + ImageContentSchema: () => ImageContentSchema, + ImplementationSchema: () => ImplementationSchema, + InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, + InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, + InitializeResultSchema: () => InitializeResultSchema, + InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, + JSONArraySchema: () => JSONArraySchema, + JSONObjectSchema: () => JSONObjectSchema, + JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, + JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, + JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, + JSONRPCRequestSchema: () => JSONRPCRequestSchema, + JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, + JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, + JSONValueSchema: () => JSONValueSchema, + LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, + ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, + ListPromptsRequestSchema: () => ListPromptsRequestSchema, + ListPromptsResultSchema: () => ListPromptsResultSchema, + ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, + ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, + ListResourcesRequestSchema: () => ListResourcesRequestSchema, + ListResourcesResultSchema: () => ListResourcesResultSchema, + ListRootsRequestSchema: () => ListRootsRequestSchema, + ListRootsResultSchema: () => ListRootsResultSchema, + ListTasksRequestSchema: () => ListTasksRequestSchema, + ListTasksResultSchema: () => ListTasksResultSchema, + ListToolsRequestSchema: () => ListToolsRequestSchema, + ListToolsResultSchema: () => ListToolsResultSchema, + LoggingLevelSchema: () => LoggingLevelSchema, + LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, + LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, + ModelHintSchema: () => ModelHintSchema, + ModelPreferencesSchema: () => ModelPreferencesSchema, + MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, + NotificationSchema: () => NotificationSchema, + NotificationsParamsSchema: () => NotificationsParamsSchema, + NumberSchemaSchema: () => NumberSchemaSchema, + PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, + PaginatedRequestSchema: () => PaginatedRequestSchema, + PaginatedResultSchema: () => PaginatedResultSchema, + PingRequestSchema: () => PingRequestSchema, + PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, + ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, + ProgressNotificationSchema: () => ProgressNotificationSchema, + ProgressSchema: () => ProgressSchema, + ProgressTokenSchema: () => ProgressTokenSchema, + PromptArgumentSchema: () => PromptArgumentSchema, + PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, + PromptMessageSchema: () => PromptMessageSchema, + PromptReferenceSchema: () => PromptReferenceSchema, + PromptSchema: () => PromptSchema, + ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, + ReadResourceRequestSchema: () => ReadResourceRequestSchema, + ReadResourceResultSchema: () => ReadResourceResultSchema, + RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, + RequestIdSchema: () => RequestIdSchema, + RequestMetaSchema: () => RequestMetaSchema, + RequestSchema: () => RequestSchema, + ResourceContentsSchema: () => ResourceContentsSchema, + ResourceLinkSchema: () => ResourceLinkSchema, + ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, + ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, + ResourceSchema: () => ResourceSchema, + ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, + ResourceTemplateSchema: () => ResourceTemplateSchema, + ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, + ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, + ResultMetaObjectSchema: () => ResultMetaObjectSchema, + ResultSchema: () => ResultSchema, + RoleSchema: () => RoleSchema, + RootSchema: () => RootSchema, + RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, + SamplingContentSchema: () => SamplingContentSchema, + SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, + SamplingMessageSchema: () => SamplingMessageSchema, + ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, + ServerNotificationSchema: () => ServerNotificationSchema, + ServerRequestSchema: () => ServerRequestSchema, + ServerResultSchema: () => ServerResultSchema, + ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, + SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, + SetLevelRequestSchema: () => SetLevelRequestSchema, + SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, + StringSchemaSchema: () => StringSchemaSchema, + SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, + SubscribeRequestSchema: () => SubscribeRequestSchema, + SubscriptionFilterSchema: () => SubscriptionFilterSchema, + SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, + SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, + SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, + SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, + SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, + SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, + TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, + TaskCreationParamsSchema: () => TaskCreationParamsSchema, + TaskMetadataSchema: () => TaskMetadataSchema, + TaskSchema: () => TaskSchema, + TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, + TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, + TaskStatusSchema: () => TaskStatusSchema, + TextContentSchema: () => TextContentSchema, + TextResourceContentsSchema: () => TextResourceContentsSchema, + TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, + ToolAnnotationsSchema: () => ToolAnnotationsSchema, + ToolChoiceSchema: () => ToolChoiceSchema, + ToolExecutionSchema: () => ToolExecutionSchema, + ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, + ToolResultContentSchema: () => ToolResultContentSchema, + ToolSchema: () => ToolSchema, + ToolUseContentSchema: () => ToolUseContentSchema, + UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, + UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, + UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, + UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema +}); + +//#endregion +//#region ../core-internal/src/types/guards.ts +/** +* Validates and parses an unknown value as a JSON-RPC message. +* +* Use this to validate incoming messages in custom transport implementations. +* Throws if the value does not conform to the JSON-RPC message schema. +* +* @param value - The value to validate (typically a parsed JSON object). +* @returns The validated {@linkcode JSONRPCMessage}. +* @throws If validation fails. +*/ +function parseJSONRPCMessage(value) { + return JSONRPCMessageSchema.parse(value); +} +const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; +const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. +*/ +const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. +*/ +const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; +/** +* Checks if a value is a valid {@linkcode CallToolResult}. +* +* This is a consumer-side VALUE check against the neutral model, not a wire +* validator: a raw wire object that additionally carries wire-only members +* (e.g. `resultType`) still passes through the loose index signature. Use a +* transport-level parse to validate raw wire traffic. +* +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. +*/ +const isCallToolResult = (value) => { + if (typeof value !== "object" || value === null || value.content === void 0) return false; + return CallToolResultSchema.safeParse(value).success; +}; +/** +* Checks whether a value is an input-required result (protocol revision +* 2026-07-28): the multi-round-trip return shape discriminated by +* `resultType: 'input_required'`. +* +* This is a discriminator check, not a full validator — the at-least-one rule +* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` +* builder and re-checked by the server seam for hand-built values. +* +* @param value - The value to check. +* @returns True if the value carries the `input_required` discriminator. +*/ +const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; +/** +* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. +* @param value - The value to check. +* +* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. +* +* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK +* runtime; kept importable for interoperability only. +*/ +const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; +const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; +const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; +function assertCompleteRequestPrompt(request) { + if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); +} +function assertCompleteRequestResourceTemplate(request) { + if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); +} + +//#endregion +//#region ../core-internal/src/shared/mcpParamHeaders.ts +/** The fixed prefix every custom-parameter header carries. */ +const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; +/** The schema-extension property name a tool's `inputSchema` carries. */ +const X_MCP_HEADER_KEY = "x-mcp-header"; +/** +* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control +* characters (including CR/LF), and the listed delimiters. +*/ +const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; +/** +* JSON Schema `type` values the spec admits on an `x-mcp-header` property. +* +* The spec text names `integer`, `string`, `boolean` and explicitly excludes +* `number`. The published conformance referee at the pinned release ships its +* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` +* parameters and expects the client to mirror them, so `number` is accepted +* here so that the conformance gate passes; the discrepancy is tracked +* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. +*/ +const PERMITTED_X_MCP_HEADER_TYPES = new Set([ + "string", + "integer", + "boolean", + "number" +]); +/** +* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations +* and validate every constraint the spec places on them. Returns either the +* collected declarations (possibly empty) or the first violated constraint. +* +* The walk descends through `properties` at any depth (the spec's "any nesting +* depth" clause). The static-reachability MUST is enforced as a structural +* sweep: every position the chain MUST NOT pass through (`items`/ +* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, +* `$defs`, `$ref` targets within `$defs`) is visited too, and an +* `x-mcp-header` found anywhere on that path invalidates the schema — "an +* annotation anywhere else makes the tool definition invalid". +*/ +function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { + const declarations = []; + const seenLower = /* @__PURE__ */ new Map(); + const visit = (node, path, reachable) => { + if (node === null || typeof node !== "object") return void 0; + const schema = node; + if (X_MCP_HEADER_KEY in schema) { + if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; + const raw = schema[X_MCP_HEADER_KEY]; + if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; + if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; + const type = typeof schema.type === "string" ? schema.type : void 0; + if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; + const lower = raw.toLowerCase(); + const prior = seenLower.get(lower); + if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; + seenLower.set(lower, raw); + declarations.push({ + path, + headerName: raw, + type + }); + } + const properties = schema.properties; + if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { + const fault$1 = visit(child, [...path, key], reachable); + if (fault$1 !== void 0) return fault$1; + } + for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { + const sub = schema[k]; + if (sub === void 0) continue; + const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; + for (const branch of branches) { + const fault$1 = visit(branch, [...path, `<${k}>`], false); + if (fault$1 !== void 0) return fault$1; + } + } + }; + const fault = visit(inputSchema, [], true); + return fault === void 0 ? { + valid: true, + declarations + } : { + valid: false, + reason: fault + }; +} +/** +* JSON Schema keywords whose subschemas the SEP-2243 static-reachability +* constraint excludes from the `properties`-only chain. An `x-mcp-header` +* found under any of these invalidates the tool definition. +*/ +const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ + "items", + "prefixItems", + "contains", + "additionalProperties", + "unevaluatedProperties", + "unevaluatedItems", + "propertyNames", + "patternProperties", + "dependentSchemas", + "oneOf", + "anyOf", + "allOf", + "not", + "if", + "then", + "else", + "$defs", + "definitions" +]; +/** +* Subschema-carrying keywords whose value is a `name → subschema` object +* (not a single subschema or array of subschemas). The visit branches over +* `Object.values()` for these. +*/ +const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ + "patternProperties", + "dependentSchemas", + "$defs", + "definitions" +]); +function pathName(path) { + return path.length === 0 ? "" : path.join("."); +} +const BASE64_SENTINEL_PREFIX = "=?base64?"; +const BASE64_SENTINEL_SUFFIX = "?="; +const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; +const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; +/** +* Convert a primitive argument value to its string representation per the +* spec's type-conversion rules: strings pass through, integers and numbers +* become their decimal string, booleans become lowercase `'true'` / `'false'`. +* Non-finite numbers and integers outside the safe range are refused (the +* caller treats `undefined` as "do not emit a header for this value"). +*/ +function mcpParamPrimitiveToString(value) { + if (typeof value === "string") return value; + if (typeof value === "boolean") return value ? "true" : "false"; + if (typeof value === "number") { + if (!Number.isFinite(value)) return void 0; + if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; + return String(value); + } +} +function base64ToUtf8(b64) { + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return new TextDecoder("utf-8", { fatal: true }).decode(bytes); +} +/** +* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, +* the payload is decoded as UTF-8; otherwise the value is returned as-is. +* Returns `undefined` when the sentinel is present but the payload is not +* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject +* such values. +*/ +function decodeMcpParamValue(value) { + if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; + const b64 = value.slice(9, value.length - 2); + if (!BASE64_CANONICAL.test(b64)) return void 0; + try { + return base64ToUtf8(b64); + } catch { + return; + } +} +function valueAtPath(root, path) { + let node = root; + for (const key of path) { + if (node === null || typeof node !== "object") return void 0; + node = node[key]; + } + return node; +} +/** +* The header/body comparison the server performs at tool-resolution time. +* +* For each `x-mcp-header` declaration on the named tool: when the body +* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be +* present and decode to an equal value; when the body value is `null` or +* absent the server MUST NOT expect the header (a present header is ignored). +* A sentinel-carrying header whose payload is not canonical Base64 / valid +* UTF-8 is rejected as invalid characters. +* +* Integer-typed declarations are compared numerically (the spec's SHOULD — +* `42.0` and `42` are equal); everything else is compared as decoded strings. +* +* Returns `undefined` when every check passes, or an +* {@linkcode InboundLadderRejection} carrying the same `-32020` +* (`HeaderMismatch`) shape the inbound classifier emits for the +* standard-header cross-checks — `400 Bad Request` with the disagreeing pair +* in `data.mismatch`. +*/ +function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { + for (const decl of declarations) { + const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; + const headerValue = headers.get(headerKey); + const bodyRaw = valueAtPath(args, decl.path); + if (bodyRaw === void 0 || bodyRaw === null) continue; + const bodyString = mcpParamPrimitiveToString(bodyRaw); + if (bodyString === void 0) continue; + if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); + const decoded = decodeMcpParamValue(headerValue); + if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); + if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); + } +} +/** +* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` +* disagreement. Same shape as the inbound classifier's standard-header +* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing +* pair, `settled: true`); only the rung differs because this check runs at the +* pre-dispatch step against a known tool's schema rather than at the edge. +*/ +function paramHeaderMismatchRejection(cell, header, body) { + return { + kind: "reject", + rung: "param-header-validation", + cell, + httpStatus: 400, + code: HEADER_MISMATCH_ERROR_CODE, + message: `Bad Request: the request headers and body disagree: ${body}`, + data: { mismatch: { + header, + body + } }, + settled: true + }; +} + +//#endregion +//#region ../core-internal/src/shared/inboundClassification.ts +/** +* Inbound HTTP request classification and the inbound validation ladder +* (protocol revision 2026-07-28). +* +* `classifyInboundRequest` is the body-primary era predicate for an HTTP +* entry that serves both protocol eras on one endpoint. It is evaluated +* exactly once, at the entry boundary, on the already-parsed request body: +* +* - `initialize` is a legacy-era request by definition (the modern era has no +* `initialize` handshake) — unless it carries a valid envelope claim naming +* a modern revision, in which case the claim wins and the request is +* classified like any other enveloped request (the modern era then answers +* it with method-not-found, exactly like every other method it does not +* define). +* - A request whose `params._meta` carries the reserved protocol-version key +* claims the per-request envelope mechanism and classifies into the era the +* named revision belongs to (a malformed envelope behind a present claim is +* a validation error, never a silent fall back to legacy handling). +* - A request without a claim is legacy-era traffic. +* - The `MCP-Protocol-Version` header is a cross-check only: it never +* upgrades or downgrades a body-derived classification, and a disagreement +* between header and body is an explicit ladder outcome. +* - Notifications carry no envelope claim of their own under the current +* spec, so for notification POSTs without a body claim the modern header is +* determinative; the `Mcp-Method` header is validated against the body when +* the message classifies modern and is never enforced on legacy traffic. +* A notification that does carry a claim is treated body-primary like a +* request, and a malformed claim is rejected the same way a request's +* malformed claim is — never silently resolved against the header. +* The notification-POST header cross-checks here are an SDK-defensive +* posture, not a spec requirement: the spec leaves header rules for posted +* notifications undefined (core client notifications do not occur over +* Streamable HTTP); applying the request rules symmetrically is what an +* ecosystem custom-notification POST expects, and the −32020 cells stay +* passing for them. +* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era +* session operations: the modern era is `POST`-only, so they are routed to +* legacy serving when it is configured and rejected otherwise. +* - Array (batch) bodies are classified element-wise: an array containing a +* modern-claiming or invalid element is rejected, an all-legacy array is +* legacy traffic unchanged, and a single-element array is still an array. +* +* The classifier returns plain values (it never throws and never touches a +* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection +* carrying the JSON-RPC error to emit and the HTTP status to emit it with. +* Legacy routing outcomes deliberately carry NO `MessageClassification` — +* legacy and hand-wired traffic is never classified, which keeps its +* dispatch behavior byte-identical to today's. +* +* Error codes for the modern-path rejection cells follow the published +* conformance suite (and the spec text it asserts): +* +* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header +* disagreeing with the body, or the `Mcp-Method` header disagreeing with the +* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. +* - A request whose protocol-version header names a modern revision but whose +* body carries no `_meta` envelope claim — including an envelope present but +* missing the required protocol-version key — is rejected with `-32602` +* (invalid params) naming the missing key(s), on HTTP 400. +* +* Should a future spec revision or conformance release change these +* assignments, the affected cells are re-derived against that release; the +* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark +* a cell provisional again while such a change is in flight. +*/ +/** +* The error code emitted for header/body cross-check mismatches: the +* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or +* with the body's classification), and the `Mcp-Method` header disagreeing +* with the body method. +* +* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 +* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted +* by the published conformance suite for header-validation failures. It has no +* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era +* wire vocabulary; the validation ladder is its only emitter. +*/ +const HEADER_MISMATCH_ERROR_CODE = -32020; +/** +* The inbound validation ladder, expressed as data rather than control flow. +* +* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the +* dispatch rungs are evaluated by the protocol layer once the classified +* message is injected into a per-request server instance (the era registry +* gate, the envelope requiredness check, and per-method params validation). +* The client-capability rung is evaluated by the HTTP entry itself, +* pre-dispatch, on the validated envelope the classifier produced — see that +* rung's rationale for the ordering caveat. The order is the precedence: a +* request that fails several rungs is answered by the earliest one. +*/ +const INBOUND_VALIDATION_LADDER = [ + { + rung: "http-method", + order: 1, + evaluatedAt: "edge", + codes: [-32e3], + conformance: [], + rationale: "The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read." + }, + { + rung: "jsonrpc-shape", + order: 2, + evaluatedAt: "edge", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest], + conformance: ["server-stateless"], + rationale: "The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic." + }, + { + rung: "era-classification", + order: 3, + evaluatedAt: "edge", + codes: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion], + conformance: [ + "server-stateless", + "http-header-validation", + "http-custom-header-server-validation" + ], + rationale: "Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions." + }, + { + rung: "envelope", + order: 4, + evaluatedAt: "edge", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: ["server-stateless"], + rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." + }, + { + rung: "method-registry", + order: 5, + evaluatedAt: "dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], + conformance: ["server-stateless"], + rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." + }, + { + rung: "request-params", + order: 6, + evaluatedAt: "dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], + conformance: [], + rationale: "Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table." + }, + { + rung: "standard-header-validation", + order: 7, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-header-validation"], + rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted." + }, + { + rung: "client-capabilities", + order: 8, + evaluatedAt: "pre-dispatch", + codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], + conformance: ["server-stateless"], + rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." + }, + { + rung: "param-header-validation", + order: 9, + evaluatedAt: "pre-dispatch", + codes: [HEADER_MISMATCH_ERROR_CODE], + conformance: ["http-custom-header-server-validation"], + rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." + } +]; +/** +* HTTP status for ladder-originated JSON-RPC error codes. +* +* Keyed on origin, not on the bare code: this table only applies to errors +* the ladder (or a pre-handler protocol gate) produced. Errors produced by +* request handlers — whatever their code — stay in-band on HTTP 200, and are +* never mapped to an HTTP status by this table; in particular `-32603` and +* domain-specific codes never become a blanket 500. The single exception is +* `MissingRequiredClientCapability` (-32021) — see +* {@linkcode httpStatusForErrorCode}. +* +* `-32602` (invalid params) deliberately has NO entry: the only invalid-params +* rejection that maps to HTTP 400 is the classifier's own envelope rung +* short-circuit, which carries its HTTP status directly. A dispatch- or +* handler-produced invalid-params error is always in-band. +*/ +const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { + [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, + [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, + [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, + [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, + [HEADER_MISMATCH_ERROR_CODE]: 400 +}; +/** +* The HTTP status to answer a JSON-RPC error with, keyed on the error's +* origin. `in-band` errors (anything produced by a request handler) are +* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP +* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), +* whose 400 the spec mandates on the error itself with no origin condition, +* and which the SDK genuinely produces after dispatch (the `input_required` +* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` +* is NOT that peer's spec error and stays in-band like every other handler +* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. +* +* The per-request transport intentionally does NOT delegate to this function: +* its `?? 400` ladder fallback is only correct for entry-gate codes known to +* the table, and would wrongly map dispatch-window errors outside it (a +* window `-32602` must stay in-band on 200). The transport indexes the table +* directly; keep the two in agreement when editing either. +*/ +function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { + if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; + return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; +} +function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { + return { + kind: "reject", + rung, + cell, + httpStatus, + code: error.code, + message: error.message, + ...error.data !== void 0 && { data: error.data }, + settled + }; +} +function crossCheckMismatch(cell, header, body, rung = "era-classification") { + return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { + header, + body + } }), true); +} +/** +* The methods whose body carries a `params.name` / `params.uri` value the +* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 +* § Standard Request Headers, `Required For` column). +*/ +const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ + "tools/call": "name", + "prompts/get": "name", + "resources/read": "uri" +})); +/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ +function stripHttpOws(value) { + let start = 0; + while (start < value.length) { + const code = value.codePointAt(start); + if (code !== 9 && code !== 32) break; + start += 1; + } + let end = value.length; + while (end > start) { + const code = value.codePointAt(end - 1); + if (code !== 9 && code !== 32) break; + end -= 1; + } + return start === 0 && end === value.length ? value : value.slice(start, end); +} +/** +* SEP-2243 standard-header server-side validation, evaluated by the HTTP +* entry on a modern-classified request immediately after +* {@linkcode classifyInboundRequest} returns a modern route. +* +* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, +* `standard-header-validation` rung — the same shape +* {@linkcode classifyInboundRequest} already emits on the edge +* `era-classification` rung for the `MCP-Protocol-Version` and +* `Mcp-Method` *mismatch* cells) when: +* +* - the required `Mcp-Method` header is absent; +* - the required `Mcp-Name` header is absent on a `tools/call`, +* `prompts/get`, or `resources/read` request whose body carries the +* `params.name` / `params.uri` value the header mirrors; +* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or +* - the (decoded) `Mcp-Name` value disagrees with the body's +* `params.name` / `params.uri`. +* +* Returns `undefined` (pass) for notifications (the spec table reads +* "All requests"), for methods that have no `Mcp-Name` source, and when the +* headers agree with the body. Never enforced on legacy traffic — the entry +* only calls this on a modern route. +* +* Kept separate from {@linkcode classifyInboundRequest} so that a body-only +* call to the classifier (no headers passed) keeps routing a modern request +* unchanged: the classifier remains a pure body-primary router, and this +* function is the presence/`Mcp-Name` half of the standard-header rung the +* entry layers on top. +*/ +function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { + if (route.messageKind !== "request") return; + const method = route.message.method; + if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); + const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; + if (sourceField === void 0) return; + const sourceValue = route.message.params?.[sourceField]; + const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; + if (request.mcpNameHeader === void 0) { + if (bodyValue === void 0) return; + return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); + } + const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); + const decoded = decodeMcpParamValue(normalizedNameHeader); + if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); + if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); +} +function isPlainObject$2(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function classificationForClaim(claimedVersion) { + if (claimedVersion === void 0) return { era: "modern" }; + return { + era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", + revision: claimedVersion + }; +} +/** +* Whether a request's params carry a per-request envelope claim that is both +* well-formed and names a modern protocol revision. +* +* Used by the `initialize` precedence rule: only such a claim overrides the +* `initialize` ⇒ legacy-handshake classification — a request carrying a valid +* modern envelope is a modern request regardless of its method name, and the +* modern era then answers `initialize` exactly like any other method it does +* not define (method-not-found). A malformed claim, or one naming a pre-2026 +* revision, keeps the legacy-handshake routing unchanged. +* +* Exported on the core internal barrel for the stdio serving entry, which +* applies the same precedence rule to a connection's opening message; not +* public API. +*/ +function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { + if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; + const meta = src_CX2iR2pK_requestMetaOf(params); + return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; +} +function classifyBatch(body) { + if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); + for (const element of body) { + if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); + if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); + } + return { + kind: "legacy", + reason: "batch" + }; +} +function classifyRequestBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { + if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); + const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "request", + message: body, + classification: classificationForClaim(claimedVersion) + }; + } + if (headerNamesModern) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); + const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; + return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); + } + return { + kind: "legacy", + reason: "no-claim", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +function classifyNotificationBody(request, body) { + const params = body.params; + const method = body.method; + const headerVersion = request.protocolVersionHeader; + const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); + if (src_CX2iR2pK_hasEnvelopeClaim(params)) { + const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); + if (claimedVersion === void 0) { + const meta = src_CX2iR2pK_requestMetaOf(params); + const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { + key: PROTOCOL_VERSION_META_KEY, + problem: "expected a protocol version string" + }; + return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); + } + if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); + const classification = classificationForClaim(claimedVersion); + if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification + }; + } + if (headerNamesModern) { + if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); + return { + kind: "modern", + messageKind: "notification", + message: body, + classification: { + era: "modern", + revision: headerVersion + } + }; + } + return { + kind: "legacy", + reason: "notification", + ...headerVersion !== void 0 && { requestedVersion: headerVersion } + }; +} +/** +* Classifies one inbound HTTP request for dual-era serving. +* +* The body-primary predicate, evaluated once at the entry boundary: see the +* module documentation for the rules. Returns a routing outcome (`legacy` or +* `modern`) or a ladder rejection; it never throws. +*/ +function src_CX2iR2pK_classifyInboundRequest(request) { + request = { + ...request, + ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, + ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, + ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } + }; + if (request.httpMethod.toUpperCase() !== "POST") return { + kind: "legacy", + reason: "http-method" + }; + const body = request.body; + if (Array.isArray(body)) return classifyBatch(body); + if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { + kind: "legacy", + reason: "response" + }; + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); + if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); + return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); +} +/** +* The rejection a modern-only endpoint (no legacy serving configured) +* answers a legacy-classified request with. +* +* - Envelope-less requests (including `initialize`) are answered with the +* unsupported-protocol-version error carrying the endpoint's supported +* versions and echoing the version the request named (when it named one — +* `requested` is omitted rather than fabricated when the request named no +* version at all), so a legacy client can discover what the endpoint serves +* from the error alone. +* - Posted responses and batch arrays are invalid requests on the modern era. +* - Non-`POST` methods are not allowed. +* - Legacy-classified notifications return `undefined`: the caller answers +* 202 with no body and does not dispatch the notification (accept-and-drop). +*/ +function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { + switch (route.reason) { + case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); + case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); + case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); + case "notification": return; + case "initialize": + case "no-claim": { + const requested = route.requestedVersion; + return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ + supported: [...supportedVersions], + requested + }), true); + } + } +} + +//#endregion +//#region ../core-internal/src/util/schema.ts +/** +* Internal Zod schema utilities for protocol handling. +* These are used internally by the SDK for protocol message validation. +*/ +/** +* Parses data against a Zod schema (synchronous). +* Returns a discriminated union with success/error. +*/ +function parseSchema(schema, data) { + return parse_safeParse(schema, data); +} +/** +* Union of the declared shape keys across several Zod object schemas. +*/ +function shapeKeys(schemas) { + return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); +} + +//#endregion +//#region ../core-internal/src/util/standardSchema.ts +/** +* Standard Schema utilities for user-provided schemas. +* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. +* @see https://standardschema.dev +*/ +function isStandardSchema(schema) { + if (schema == null) return false; + const schemaType = typeof schema; + if (schemaType !== "object" && schemaType !== "function") return false; + if (!("~standard" in schema)) return false; + return typeof schema["~standard"]?.validate === "function"; +} +let warnedZodFallback = false; +/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ +const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; +/** +* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. +* +* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt +* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). +* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, +* so for `io: 'input'` this function defaults `type` to `"object"` when absent +* and throws on an explicit non-object `type` (e.g. `z.string()`). For +* `io: 'output'` a non-object root is returned as-is; the `"object"` default is +* applied only when the root is provably object-shaped. +*/ +function standardSchemaToJsonSchema(schema, io = "input") { + const std = schema["~standard"]; + let result; + if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); + else if (std.vendor === "zod") { + if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema()."); + if (!warnedZodFallback) { + warnedZodFallback = true; + console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning."); + } + result = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io + }); + } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); + if (io === "output") { + if (result.type !== void 0) return result; + return isProvablyObjectShapedRoot(result) ? { + type: "object", + ...result + } : result; + } + if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); + return { + type: "object", + ...result + }; +} +/** +* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords +* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a +* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively +* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to +* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. +*/ +function isProvablyObjectShapedRoot(schema) { + if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; + for (const key of [ + "oneOf", + "anyOf", + "allOf" + ]) { + const members = schema[key]; + if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); + } + return false; +} +function formatIssue(issue) { + if (!issue.path?.length) return issue.message; + return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; +} +async function validateStandardSchema(schema, data) { + const result = await schema["~standard"].validate(data); + if (result.issues && result.issues.length > 0) return { + success: false, + error: result.issues.map((i) => formatIssue(i)).join(", ") + }; + return { + success: true, + data: result.value + }; +} +function zodEmittedPattern(schema) { + const jsonSchema = toJSONSchema(schema, { + target: JSON_SCHEMA_CONVERSION_TARGET, + io: "input" + }); + return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; +} +const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; +function datetimeReferenceSchemas(pattern) { + const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); + const precisions = [ + void 0, + -1, + 0 + ]; + if (fractionDigits) precisions.push(Number(fractionDigits[1])); + return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ + local, + offset, + precision + })))); +} +function referencePatternsForFormat(format, pattern) { + let referenceSchemas; + switch (format) { + case "email": + referenceSchemas = [schemas_email()]; + break; + case "uri": + referenceSchemas = [schemas_url()]; + break; + case "date": + referenceSchemas = [iso_date()]; + break; + case "date-time": + referenceSchemas = datetimeReferenceSchemas(pattern); + break; + } + return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); +} +/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ +function isLibraryFormatPattern(format, pattern, vendor) { + if (vendor !== "zod") return true; + return referencePatternsForFormat(format, pattern).has(pattern); +} +function promptArgumentsFromStandardSchema(schema) { + const jsonSchema = standardSchemaToJsonSchema(schema, "input"); + const properties = jsonSchema.properties || {}; + const required = jsonSchema.required || []; + return Object.entries(properties).map(([name, prop]) => ({ + name, + description: prop?.description, + required: required.includes(name) + })); +} + +//#endregion +//#region ../core-internal/src/shared/elicitation.ts +function isJsonObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +function convertStandardElicitationSchema(schema) { + try { + return standardSchemaToJsonSchema(schema, "input"); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); + } +} +const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ + "$comment", + "deprecated", + "description", + "examples", + "readOnly", + "title", + "writeOnly" +]); +function isAnnotationOnlyJsonSchemaKeyword(key) { + return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); +} +const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); +const PROPERTY_KEYS_BY_TYPE = { + string: shapeKeys([ + StringSchemaSchema, + UntitledSingleSelectEnumSchemaSchema, + TitledSingleSelectEnumSchemaSchema, + LegacyTitledEnumSchemaSchema + ]), + number: shapeKeys([NumberSchemaSchema]), + integer: shapeKeys([NumberSchemaSchema]), + boolean: shapeKeys([BooleanSchemaSchema]), + array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) +}; +const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); +/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ +function walkProperty(node, path, vendor, unsupported) { + if (!isJsonObject(node)) return node; + const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; + if (allowedKeys === void 0) return node; + const pruned = {}; + for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; + else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { + if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; + else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); + } else unsupported.push(`${path}.${key}`); + return pruned; +} +/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ +function walkRequestedSchema(converted, vendor) { + const pruned = {}; + const unsupported = []; + for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); + else if (ROOT_KEYS.has(key)) pruned[key] = value; + else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); + if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); + return pruned; +} +/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ +function describeUnsupportedProperties(pruned, fallback) { + if (!isJsonObject(pruned.properties)) return fallback; + const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); + return offenders.length > 0 ? offenders.join(", ") : fallback; +} +function findDroppedConstraintPaths(original, parsed, path = "") { + if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); + if (!isJsonObject(original) || !isJsonObject(parsed)) return []; + return Object.entries(original).flatMap(([key, value]) => { + const childPath = path ? `${path}.${key}` : key; + if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; + return findDroppedConstraintPaths(value, parsed[key], childPath); + }); +} +/** Converts an authoring-friendly elicitation input into its wire-ready form. */ +function normalizeElicitInputParams(input) { + if (!isStandardSchema(input.requestedSchema)) return { + ...input, + mode: "form", + requestedSchema: input.requestedSchema + }; + const vendor = input.requestedSchema["~standard"].vendor; + const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); + const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); + const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); + if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); + const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); + if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); + return { + ...input, + mode: "form", + requestedSchema: parsed.data + }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequired.ts +/** +* Authoring helpers for multi-round-trip requests (protocol revision +* 2026-07-28). +* +* A handler for one of the multi-round-trip methods (`tools/call`, +* `prompts/get`, `resources/read`) requests additional client input by +* returning an {@linkcode InputRequiredResult} instead of a final result. The +* helpers here build that return value and its embedded requests as NEUTRAL +* values; only the 2026-07-28 wire codec maps them to/from the wire. The +* 2025-era codec has no input-required vocabulary — on a 2025-era request the +* server's legacy shim (on by default) fulfils the embedded requests as real +* server→client requests and re-enters the handler, so the same return shape +* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores +* the pre-shim loud failure. +* +* There is no nominal brand: `resultType: 'input_required'` is the +* discriminator, and hand-built result literals are equally legal — the +* server seam re-checks the at-least-one rule for them. +*/ +function buildInputRequired(spec) { + const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; + const hasRequestState = typeof spec.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)"); + return { + resultType: "input_required", + ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, + ...spec.requestState !== void 0 && { requestState: spec.requestState } + }; +} +/** +* Builder for the input-required return value of multi-round-trip handlers, +* with per-kind constructors for the embedded requests +* (`inputRequired.elicit`, `inputRequired.elicitUrl`, +* `inputRequired.createMessage`, `inputRequired.listRoots`). +* +* @example Write-once tool requesting confirmation +* ```ts +* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { +* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); +* if (!confirmed) { +* return inputRequired({ +* inputRequests: { +* confirm: inputRequired.elicit({ +* message: `Deploy to ${env}?`, +* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } +* }) +* } +* }); +* } +* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; +* }); +* ``` +*/ +const inputRequired = Object.assign(buildInputRequired, { + elicit(params) { + try { + return { + method: "elicitation/create", + params: normalizeElicitInputParams(params) + }; + } catch (error) { + throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; + } + }, + elicitUrl(params) { + return { + method: "elicitation/create", + params: { + ...params, + mode: "url" + } + }; + }, + createMessage(params) { + return { + method: "sampling/createMessage", + params + }; + }, + listRoots() { + return { method: "roots/list" }; + } +}); +function acceptedContent(responses, key, schema) { + const view = inputResponse(responses, key); + if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; + if (schema === void 0) return view.content; + const outcome = schema["~standard"].validate(view.content); + if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); + return outcome.issues === void 0 ? outcome.value : void 0; +} +/** +* Reads one entry of a retried request's `inputResponses` +* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering +* decline/cancel detection and the non-elicitation response kinds that +* {@linkcode acceptedContent} does not surface. +* +* The values arrive from the client and are not re-validated here — treat +* them as untrusted input (validate elicitation content with the +* schema-aware {@linkcode acceptedContent} overload where it matters). +*/ +function inputResponse(responses, key) { + if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; + const entry = responses[key]; + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; + const candidate = entry; + if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { + const content = candidate["content"]; + return { + kind: "elicit", + action: candidate["action"], + ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } + }; + } + if (Array.isArray(candidate["roots"])) return { + kind: "roots", + roots: candidate["roots"] + }; + if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { + kind: "sampling", + result: candidate + }; + return { kind: "missing" }; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredDriver.ts +/** +* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). +* +* When a request to one of the multi-round-trip methods comes back as +* `input_required`, the driver fulfils the embedded input requests by +* dispatching them to the client's already-registered handlers (elicitation, +* sampling, roots — one generic engine, no per-feature API), then retries the +* original request with the collected `inputResponses` and a byte-exact echo +* of `requestState`, on a fresh request id, until the server returns a +* complete result or the round cap is exhausted. +* +* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the +* same primitive a manual caller uses (`allowInputRequired` semantics — the +* retry hands back the next `input_required` payload instead of recursing), +* so the loop, the cap, and the pacing live in one place and disabling +* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this +* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to +* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by +* shrinking the budget passed to each leg — no new timer system. +*/ +/** +* Fixed pacing applied before retrying a requestState-only (load-shedding) +* leg — a leg that carries no embedded input requests, so nothing slows the +* loop down naturally. Counted in the same round cap. +*/ +const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; +/** +* The message both multi-round-trip loops emit when the round cap is +* exhausted — the client driver as a typed error, the server-side legacy +* shim as its per-family failure. One formatter so the texts cannot drift +* (hosts and models read the tool-result copy verbatim). +*/ +function inputRequiredRoundsExceededMessage(method, maxRounds) { + return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; +} +/** +* Abortable delay: resolves after `ms`, or rejects with the signal's reason +* (wrapped in an `SdkError` when it isn't already one) if the signal aborts +* first. Aborting after resolution is a no-op. Shared with the server-side +* legacy shim (the pacing semantics must match per era). +*/ +function sleep(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); + return; + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort); + resolve(); + }, ms); + const onAbort = () => { + clearTimeout(timer); + reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); + }; + signal?.addEventListener("abort", onAbort, { once: true }); + }); +} +/** +* A per-round abort linked to the caller's signal: the embedded sibling +* dispatches share it, so the first failure (or a caller abort) cancels the +* others instead of leaving them running. Shared with the server-side legacy +* shim (the abort-linkage semantics must match per era). +*/ +function linkedRoundAbort(outer) { + const controller = new AbortController(); + const onOuterAbort = () => controller.abort(outer?.reason); + outer?.addEventListener("abort", onOuterAbort, { once: true }); + if (outer?.aborted) controller.abort(outer.reason); + return { + signal: controller.signal, + abort: (reason) => controller.abort(reason), + dispose: () => outer?.removeEventListener("abort", onOuterAbort) + }; +} + +//#endregion +//#region ../core-internal/src/types/specTypeSchema.ts +/** +* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. +* +* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no +* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, +* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). +* Keeping the list explicit means new public spec types must be added here deliberately, and +* internals never leak into `SpecTypeName`. +* +* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` +* (the bare name collides with the server package's `ResourceTemplate` class), so +* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to +* a type literally named `ResourceTemplate`. +*/ +const SPEC_SCHEMA_KEYS = [ + "AnnotationsSchema", + "AudioContentSchema", + "BaseMetadataSchema", + "BlobResourceContentsSchema", + "BooleanSchemaSchema", + "CallToolRequestSchema", + "CallToolRequestParamsSchema", + "CallToolResultSchema", + "CancelledNotificationSchema", + "CancelledNotificationParamsSchema", + "CancelTaskRequestSchema", + "CancelTaskResultSchema", + "ClientCapabilitiesSchema", + "ClientNotificationSchema", + "ClientRequestSchema", + "ClientResultSchema", + "CompatibilityCallToolResultSchema", + "CompleteRequestSchema", + "CompleteRequestParamsSchema", + "CompleteResultSchema", + "ContentBlockSchema", + "CreateMessageRequestSchema", + "CreateMessageRequestParamsSchema", + "CreateMessageResultSchema", + "CreateMessageResultWithToolsSchema", + "CreateTaskResultSchema", + "CursorSchema", + "DiscoverRequestSchema", + "DiscoverResultSchema", + "ElicitationCompleteNotificationSchema", + "ElicitationCompleteNotificationParamsSchema", + "ElicitRequestSchema", + "ElicitRequestFormParamsSchema", + "ElicitRequestParamsSchema", + "ElicitRequestURLParamsSchema", + "ElicitResultSchema", + "EmbeddedResourceSchema", + "EmptyResultSchema", + "EnumSchemaSchema", + "GetPromptRequestSchema", + "GetPromptRequestParamsSchema", + "GetPromptResultSchema", + "GetTaskPayloadRequestSchema", + "GetTaskPayloadResultSchema", + "GetTaskRequestSchema", + "GetTaskResultSchema", + "IconSchema", + "IconsSchema", + "ImageContentSchema", + "ImplementationSchema", + "InitializedNotificationSchema", + "InitializeRequestSchema", + "InitializeRequestParamsSchema", + "InitializeResultSchema", + "JSONArraySchema", + "JSONObjectSchema", + "JSONRPCErrorResponseSchema", + "JSONRPCMessageSchema", + "JSONRPCNotificationSchema", + "JSONRPCRequestSchema", + "JSONRPCResponseSchema", + "JSONRPCResultResponseSchema", + "JSONValueSchema", + "LegacyTitledEnumSchemaSchema", + "ListPromptsRequestSchema", + "ListPromptsResultSchema", + "ListResourcesRequestSchema", + "ListResourcesResultSchema", + "ListResourceTemplatesRequestSchema", + "ListResourceTemplatesResultSchema", + "ListRootsRequestSchema", + "ListRootsResultSchema", + "ListTasksRequestSchema", + "ListTasksResultSchema", + "ListToolsRequestSchema", + "ListToolsResultSchema", + "LoggingLevelSchema", + "LoggingMessageNotificationSchema", + "LoggingMessageNotificationParamsSchema", + "ModelHintSchema", + "ModelPreferencesSchema", + "MultiSelectEnumSchemaSchema", + "NotificationSchema", + "NumberSchemaSchema", + "PaginatedRequestSchema", + "PaginatedRequestParamsSchema", + "PaginatedResultSchema", + "PingRequestSchema", + "PrimitiveSchemaDefinitionSchema", + "ProgressSchema", + "ProgressNotificationSchema", + "ProgressNotificationParamsSchema", + "ProgressTokenSchema", + "PromptSchema", + "PromptArgumentSchema", + "PromptListChangedNotificationSchema", + "PromptMessageSchema", + "PromptReferenceSchema", + "ReadResourceRequestSchema", + "ReadResourceRequestParamsSchema", + "ReadResourceResultSchema", + "RelatedTaskMetadataSchema", + "RequestSchema", + "RequestIdSchema", + "RequestMetaSchema", + "ResourceSchema", + "ResourceContentsSchema", + "ResourceLinkSchema", + "ResourceListChangedNotificationSchema", + "ResourceRequestParamsSchema", + "ResourceTemplateSchema", + "ResourceTemplateReferenceSchema", + "ResourceUpdatedNotificationSchema", + "ResourceUpdatedNotificationParamsSchema", + "ResultMetaObjectSchema", + "ResultSchema", + "RoleSchema", + "RootSchema", + "RootsListChangedNotificationSchema", + "SamplingContentSchema", + "SamplingMessageSchema", + "SamplingMessageContentBlockSchema", + "ServerCapabilitiesSchema", + "ServerNotificationSchema", + "ServerRequestSchema", + "ServerResultSchema", + "SetLevelRequestSchema", + "SetLevelRequestParamsSchema", + "SingleSelectEnumSchemaSchema", + "StringSchemaSchema", + "SubscribeRequestSchema", + "SubscribeRequestParamsSchema", + "SubscriptionFilterSchema", + "SubscriptionsAcknowledgedNotificationSchema", + "SubscriptionsAcknowledgedNotificationParamsSchema", + "SubscriptionsListenRequestSchema", + "SubscriptionsListenRequestParamsSchema", + "SubscriptionsListenResultSchema", + "SubscriptionsListenResultMetaSchema", + "TaskAugmentedRequestParamsSchema", + "TaskCreationParamsSchema", + "TaskMetadataSchema", + "TaskSchema", + "TaskStatusSchema", + "TaskStatusNotificationSchema", + "TaskStatusNotificationParamsSchema", + "TextContentSchema", + "TextResourceContentsSchema", + "TitledMultiSelectEnumSchemaSchema", + "TitledSingleSelectEnumSchemaSchema", + "ToolSchema", + "ToolAnnotationsSchema", + "ToolChoiceSchema", + "ToolExecutionSchema", + "ToolListChangedNotificationSchema", + "ToolResultContentSchema", + "ToolUseContentSchema", + "UnsubscribeRequestSchema", + "UnsubscribeRequestParamsSchema", + "UntitledMultiSelectEnumSchemaSchema", + "UntitledSingleSelectEnumSchemaSchema" +]; +const authSchemas = { + IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, + OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, + OAuthClientInformationSchema: OAuthClientInformationSchema, + OAuthClientMetadataSchema: OAuthClientMetadataSchema, + OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, + OAuthErrorResponseSchema: OAuthErrorResponseSchema, + OAuthMetadataSchema: OAuthMetadataSchema, + OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, + OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, + OAuthTokensSchema: OAuthTokensSchema, + OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, + OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema +}; +const _specTypeSchemas = {}; +const _isSpecType = {}; +function register(key, schema) { + const name = key.slice(0, -6); + _specTypeSchemas[name] = schema; + _isSpecType[name] = (v) => schema.safeParse(v).success; +} +for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); +for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); +/** +* Runtime validators for every MCP spec type, keyed by type name. +* +* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for +* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from +* storage that should be a `Tool`. +* +* Each entry implements the Standard Schema interface, so it composes with any +* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" +* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); +* if (result.issues === undefined) { +* // result.value is CallToolResult +* } +* ``` +*/ +const specTypeSchemas = Object.freeze(_specTypeSchemas); +/** +* Type predicates for every MCP spec type, keyed by type name. +* +* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and +* transforms are applied), and narrows to that input type. For schemas with `.default()` or +* `.preprocess()`, this may accept values that do not structurally match the named output type; +* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use +* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. +* +* Each guard is a standalone function, so it can be passed directly as a callback. +* +* @example +* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" +* if (isSpecType.ContentBlock(value)) { +* // value is ContentBlock +* } +* +* const blocks = mixed.filter(isSpecType.ContentBlock); +* ``` +*/ +const isSpecType = Object.freeze(_isSpecType); + +//#endregion +//#region ../core-internal/src/wire/bootstrap.ts +function bootstrapOutboundCodec(method) { + switch (method) { + case "initialize": + case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); + case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); + default: return; + } +} + +//#endregion +//#region ../core-internal/src/shared/protocol.ts +/** +* The default request timeout, in milliseconds. +*/ +const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; +/** +* The reserved per-request `_meta` envelope keys (protocol revision +* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before +* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are +* wire-level bookkeeping, not handler material. +*/ +const RESERVED_ENVELOPE_META_KEYS = [ + auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, + auth_CUe6YdwF_CLIENT_INFO_META_KEY, + auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, + LOG_LEVEL_META_KEY +]; +/** +* Top-level params members carrying multi-round-trip driver material +* (protocol revision 2026-07-28). The spec reserves these names on +* client-initiated REQUESTS only — notification params keep them untouched +* (a vendor notification may legitimately use the same names). +*/ +const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; +/** +* Lift wire-only material out of an inbound message so handlers see exactly +* the 2025-era shape, and surface it for the protocol layer (requests: via +* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the +* reserved envelope `_meta` keys are reserved on every message, while the +* multi-round-trip retry fields (`inputResponses`/`requestState`) are +* reserved on client-initiated requests only — so notifications get only the +* envelope lift, and their top-level params stay untouched. Messages without +* wire-only material are returned unchanged (same reference). +*/ +function liftWireOnlyMaterial(message, kind) { + const params = message.params; + if (!isPlainObject$1(params)) return { + message, + lifted: {} + }; + const meta = params._meta; + const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; + const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; + if (envelopeKeys.length === 0 && retryKeys.length === 0) return { + message, + lifted: {} + }; + const lifted = {}; + const nextParams = { ...params }; + if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { + const envelope = {}; + const nextMeta = { ...meta }; + for (const key of envelopeKeys) { + envelope[key] = meta[key]; + delete nextMeta[key]; + } + lifted.envelope = envelope; + if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; + else delete nextParams._meta; + } + for (const key of retryKeys) { + if (key === "inputResponses") lifted.inputResponses = nextParams[key]; + if (key === "requestState") lifted.requestState = nextParams[key]; + delete nextParams[key]; + } + return { + message: { + ...message, + params: nextParams + }, + lifted + }; +} +/** +* Standard Schema adapter over the era codec's `validateResult` function (the +* function-only WireCodec contract exposes no schema objects). Used by the +* spec-method `request()` overload so the request funnel keeps a single +* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema +* paths. +* +* Returns `undefined` when the method has no result entry on this era's +* registry — the caller maps that to the synchronous "pass a result schema" +* TypeError, exactly matching the pre-function-only behavior the +* typedMapAlignment suite pins (the result map deliberately excludes the +* `tasks/*` methods, so the spec-method overload refuses them up front). +*/ +function codecResultValidator(codec, method) { + const probe = codec.validateResult(method, void 0); + if (!probe.ok && probe.reason === "not-in-era") return void 0; + return { "~standard": { + version: 1, + vendor: "mcp-wire-codec", + validate(value) { + const outcome = codec.validateResult(method, value); + if (outcome.ok) return { value: outcome.value }; + return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; + } + } }; +} +/** +* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The +* `as T` below is the one place {@linkcode RequestStateAccessor}'s +* caller-asserted typing is implemented — no implementation can produce an +* arbitrary `T` from a runtime value honestly. +*/ +function requestStateAccessor(value) { + return () => value; +} +/** Shared no-state accessor: the common case allocates nothing per request. */ +const NO_REQUEST_STATE = requestStateAccessor(void 0); +/** +* Returns a context whose `requestState` accessor reads the given value — +* how the server seam hands a verify hook's decoded payload (or the legacy +* shim's per-round echo) to the handler without mutating the original +* context. +*/ +function withRequestStateValue(ctx, value) { + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + requestState: requestStateAccessor(value) + } + }; +} +let writeNegotiatedProtocolVersion; +/** +* Package-internal write channel for a {@linkcode Protocol} instance's +* negotiated protocol version, for callers outside the class hierarchy: +* tests and the (future) modern-era server entry that marks a factory +* instance modern at binding time. Exported on the core internal barrel +* only — never public API. +*/ +function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { + writeNegotiatedProtocolVersion(instance, version); +} +/** +* Implements MCP protocol framing on top of a pluggable transport, including +* features like request/response linking, notifications, and progress. +* +* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific +* implementations most code should use. +*/ +var Protocol = class { + _transport; + _requestMessageId = 0; + _requestHandlers = /* @__PURE__ */ new Map(); + _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + _notificationHandlers = /* @__PURE__ */ new Map(); + _responseHandlers = /* @__PURE__ */ new Map(); + _progressHandlers = /* @__PURE__ */ new Map(); + _timeoutInfo = /* @__PURE__ */ new Map(); + _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); + /** + * The protocol version negotiated for the current connection (`undefined` + * before negotiation completes), which determines the wire era this + * instance speaks. Set by the SDK's negotiation and initialize paths + * (`Client.connect`, `Server._oninitialize`). + */ + _negotiatedProtocolVersion; + static { + writeNegotiatedProtocolVersion = (instance, version) => { + instance._negotiatedProtocolVersion = version; + }; + } + _supportedProtocolVersions; + /** + * Callback for when the connection is closed for any reason. + * + * This is invoked when {@linkcode Protocol.close | close()} is called as well. + */ + onclose; + /** + * Callback for when an error occurs. + * + * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. + */ + onerror; + /** + * A handler to invoke for any request types that do not have their own handler installed. + */ + fallbackRequestHandler; + /** + * A handler to invoke for any notification types that do not have their own handler installed. + */ + fallbackNotificationHandler; + constructor(_options) { + this._options = _options; + this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; + this.setNotificationHandler("notifications/cancelled", (notification) => { + this._oncancel(notification); + }); + this.setNotificationHandler("notifications/progress", (notification) => { + this._onprogress(notification); + }); + this.setRequestHandler("ping", (_request) => ({})); + } + /** + * Drop consult for inbound messages whose transport did not classify them + * at the edge — long-lived channels such as stdio, where a role class may + * need to decline traffic the negotiated era has no answer for (the + * client-side inbound-request drop on modern-era connections: the + * 2026-07-28 era has no server→client request channel, and on stdio the + * client must never write JSON-RPC responses). + * + * Consulted ONLY when the transport supplied no + * {@linkcode MessageExtraInfo.classification}: edge-classified traffic + * never reaches the hook. Returning `'drop'` discards the message without + * writing any response (requests are surfaced via `onerror`). The base + * implementation returns `undefined`: unclassified traffic keeps today's + * dispatch path unchanged. Era selection never happens here — era is + * instance state, owned by the serving entry that constructed and + * connected the instance. + */ + _shouldDropInbound(_message) {} + /** + * The per-request `_meta` envelope this instance attaches to every outgoing + * request and notification, when one applies. The base implementation + * returns `undefined` (no envelope — the 2025-era posture, so legacy-era + * outbound traffic is byte-identical to a build without this seam). + * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) + * era to return the reserved protocol-version / client-info / + * client-capabilities keys. User-supplied `_meta` keys take precedence over + * the auto-attached ones. + */ + _outboundMetaEnvelope() {} + /** + * Attach this instance's outbound `_meta` envelope (when one is configured) + * to a request or notification. A no-op when the seam returns `undefined` + * — the message returns by reference, so the legacy-era wire stays + * byte-identical. User-supplied `_meta` keys are spread last so they win + * over the auto-attached envelope keys. + */ + _envelopeOutbound(message) { + const envelope = this._outboundMetaEnvelope(); + if (envelope === void 0) return message; + const params = message.params ?? {}; + return { + ...message, + params: { + ...params, + _meta: { + ...envelope, + ...params._meta + } + } + }; + } + /** + * Extension point for non-`complete` decoded results in the response + * funnel: a result the wire codec discriminated into a kind other than + * `'complete'` or `'invalid'` is handed here for the role class to + * resolve. The base default surfaces it as a typed + * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). + * + * Intended consumers (named so the seam stays accountable): + * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils + * `'input_required'` results through the registered + * elicitation/sampling/roots handlers and retries via `flow.retry`; + * - a future client-side terminal-result handler for + * `subscriptions/listen`, when the spec defines one. + * + * `Server` instances never receive `input_required` responses on their + * outbound legs and leave the base behavior in place. + */ + _resolveNonCompleteResult(decoded, flow) { + return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { + resultType: decoded.kind, + method: flow.request.method + })); + } + /** + * Protected accessor for a registered request handler. Used by role + * classes that dispatch synthesized requests through the same stored + * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip + * input request). + */ + _getRequestHandler(method) { + return this._requestHandlers.get(method); + } + async _oncancel(notification) { + if (!notification.params.requestId) return; + this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); + } + _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { + this._timeoutInfo.set(messageId, { + timeoutId: setTimeout(onTimeout, timeout), + startTime: Date.now(), + timeout, + maxTotalTimeout, + resetTimeoutOnProgress, + onTimeout + }); + } + _resetTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (!info) return false; + const totalElapsed = Date.now() - info.startTime; + if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { + this._timeoutInfo.delete(messageId); + throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { + maxTotalTimeout: info.maxTotalTimeout, + totalElapsed + }); + } + clearTimeout(info.timeoutId); + info.timeoutId = setTimeout(info.onTimeout, info.timeout); + return true; + } + _cleanupTimeout(messageId) { + const info = this._timeoutInfo.get(messageId); + if (info) { + clearTimeout(info.timeoutId); + this._timeoutInfo.delete(messageId); + } + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + */ + async connect(transport) { + this._transport = transport; + const _onclose = this.transport?.onclose; + this._transport.onclose = () => { + try { + _onclose?.(); + } finally { + this._onclose(); + } + }; + const _onerror = this.transport?.onerror; + this._transport.onerror = (error) => { + _onerror?.(error); + this._onerror(error); + }; + const _onmessage = this._transport?.onmessage; + this._transport.onmessage = (message, extra) => { + _onmessage?.(message, extra); + if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); + else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); + else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); + else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); + }; + transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); + await this._transport.start(); + } + /** + * Transport-close hook. Subclass overrides MUST call `super._onclose()` + * after their own cleanup — base teardown (response-handler settlement, + * timeout clearing, in-flight request abort) does not run otherwise. + */ + _onclose() { + const responseHandlers = this._responseHandlers; + this._responseHandlers = /* @__PURE__ */ new Map(); + this._progressHandlers.clear(); + this._pendingDebouncedNotifications.clear(); + for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); + this._timeoutInfo.clear(); + const requestHandlerAbortControllers = this._requestHandlerAbortControllers; + this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); + const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); + this._transport = void 0; + try { + this.onclose?.(); + } finally { + for (const handler of responseHandlers.values()) handler(error); + for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); + } + } + _onerror(error) { + this.onerror?.(error); + } + /** + * Inbound-notification dispatch. Subclass overrides MUST delegate + * unmatched traffic to `super._onnotification(rawNotification, extra)` — + * an override that consumes only what it owns and falls through to base + * dispatch for everything else. + */ + _onnotification(rawNotification, extra) { + const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); + return; + } + } + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; + const handler = this._notificationHandlers.get(notification.method); + const fallback = this.fallbackNotificationHandler; + if (handler === void 0 && fallback === void 0) return; + Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); + } + _onrequest(rawRequest, extra) { + const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); + const codec = this._negotiatedWireCodec(); + if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { + this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); + return; + } + const capturedTransport = this._transport; + const sendErrorResponse = (code, message, data) => { + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }; + capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); + }; + if (extra?.classification !== void 0) { + const classified = classifiedWireEra(extra.classification); + if (classified !== codec.era) { + this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); + const requested = extra.classification.revision ?? classified; + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { + supported: this._supportedProtocolVersions, + requested + }); + return; + } + } + if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; + if (handler === void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); + return; + } + const envelopeError = codec.checkInboundEnvelope(lifted); + if (envelopeError !== void 0) { + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); + return; + } + const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { + ...options, + relatedRequestId: request.id + }); + const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { + ...options, + relatedRequestId: request.id + }); + const abortController = new AbortController(); + this._requestHandlerAbortControllers.set(request.id, abortController); + const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); + const baseCtx = { + sessionId: capturedTransport?.sessionId, + mcpReq: { + id: request.id, + method: request.method, + _meta: request.params?._meta, + ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, + ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, + ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, + requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), + signal: abortController.signal, + send: ((r, schemaOrOptions, maybeOptions) => { + const sendCodec = this._resolveOutboundCodec(r.method); + this._assertOutboundRequestInEra(sendCodec, r.method); + if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(sendCodec, r.method); + if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); + return sendRequest(r, validate, schemaOrOptions); + }), + notify: sendNotification + }, + http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 + }; + const ctx = this.buildContext(baseCtx, extra); + Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { + if (abortController.signal.aborted) return; + let encoded; + try { + encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); + } catch (error) { + this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); + sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); + return; + } + const response = { + result: encoded, + jsonrpc: "2.0", + id: request.id + }; + await capturedTransport?.send(response); + }, async (error) => { + if (abortController.signal.aborted) return; + const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; + const errorResponse = { + jsonrpc: "2.0", + id: request.id, + error: { + code: codec.encodeErrorCode(thrownCode), + message: error.message ?? "Internal error", + ...error["data"] !== void 0 && { data: error["data"] } + } + }; + await capturedTransport?.send(errorResponse); + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { + if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); + }); + } + _onprogress(notification) { + const { progressToken, ...params } = notification.params; + const messageId = Number(progressToken); + const handler = this._progressHandlers.get(messageId); + if (!handler) { + this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); + return; + } + const responseHandler = this._responseHandlers.get(messageId); + const timeoutInfo = this._timeoutInfo.get(messageId); + if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { + this._resetTimeout(messageId); + } catch (error) { + this._responseHandlers.delete(messageId); + this._progressHandlers.delete(messageId); + this._cleanupTimeout(messageId); + responseHandler(error); + return; + } + handler(params); + } + /** + * Inbound-response dispatch. Subclass overrides MUST delegate unmatched + * traffic to `super._onresponse(response)` — an override that consumes + * only what it owns and falls through to base dispatch for everything + * else. + */ + _onresponse(response) { + const messageId = Number(response.id); + const handler = this._responseHandlers.get(messageId); + if (handler === void 0) { + this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); + return; + } + this._responseHandlers.delete(messageId); + this._cleanupTimeout(messageId); + this._progressHandlers.delete(messageId); + if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); + else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); + } + get transport() { + return this._transport; + } + /** + * Closes the connection. + */ + async close() { + await this._transport?.close(); + } + request(request, schemaOrOptions, maybeOptions) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); + const validate = codecResultValidator(codec, request.method); + if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); + return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); + } + /** + * The wire codec for this instance's negotiated era — the phase-2 truth: + * everything an established connection sends and receives resolves + * through it. Legacy until a version has been negotiated. + */ + _negotiatedWireCodec() { + return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + } + /** + * Protected accessor for the instance's negotiated wire codec, for role + * classes (Client/Server/McpServer) routing era-dependent behavior + * through the codec's function-only surface — `samplingResultVariant`, + * `outboundEnvelope`, `projectCallToolResult` — instead of branching on + * the protocol version themselves. + */ + _wireCodec() { + return this._negotiatedWireCodec(); + } + /** + * Outbound codec resolution: while the negotiated version is still unset + * (the negotiation window), lifecycle messages are bootstrap-pinned BY + * METHOD — they self-identify their era (`initialize` IS the legacy + * handshake, `server/discover` IS the modern probe). Once a version has + * been negotiated, the instance era is authoritative for everything — a + * negotiated session never re-routes a method onto the other era. + */ + _resolveOutboundCodec(method) { + if (this._negotiatedProtocolVersion === void 0) { + const pinned = bootstrapOutboundCodec(method); + if (pinned) return pinned; + } + return this._negotiatedWireCodec(); + } + /** + * Era gate for outbound requests — deletions are physical in BOTH + * directions: sending a spec method that the resolved era does not define + * dies locally with a typed error before anything reaches the transport. + * Methods outside the spec universe are consumer-owned extension methods + * and stay era-blind. + */ + _assertOutboundRequestInEra(codec, method) { + if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method, + era: codec.era + }); + } + /** + * Sends a request and waits for a response, using the provided schema for + * validation instead of the era registry's method-keyed entry. + * + * This is the internal implementation used by SDK methods whose result + * schema cannot be expressed as a method-keyed registry entry — the one + * surviving case is `server.createMessage`, whose result schema depends + * on the REQUEST params (tools vs no tools) — and by callers passing + * explicit compatibility schemas. Spec methods are still era-gated here: + * an explicit schema never smuggles a deleted method onto the wire. + */ + _requestWithSchema(request, resultSchema, options) { + const codec = this._resolveOutboundCodec(request.method); + this._assertOutboundRequestInEra(codec, request.method); + return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); + } + /** + * The request funnel proper, keyed by the resolved era codec: the codec + * owns result decoding (raw-first `resultType` discrimination — V-1 — + * and the era's lift posture) before the schema validation step. + */ + _requestWithSchemaViaCodec(codec, request, resultSchema, options) { + const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; + const flowStartedAt = Date.now(); + let onAbort; + let cleanupMessageId; + return new Promise((resolve, reject) => { + const earlyReject = (error) => { + reject(error); + }; + if (!this._transport) { + earlyReject(/* @__PURE__ */ new Error("Not connected")); + return; + } + if (this._options?.enforceStrictCapabilities === true) try { + this.assertCapabilityForMethod(request.method); + } catch (error) { + earlyReject(error); + return; + } + if (options?.signal?.aborted) { + const reason = options.signal.reason; + throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); + } + const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; + const messageId = this._requestMessageId++; + cleanupMessageId = messageId; + const jsonrpcRequest = { + ...request, + jsonrpc: "2.0", + id: messageId + }; + if (options?.onprogress) { + this._progressHandlers.set(messageId, options.onprogress); + jsonrpcRequest.params = { + ...request.params, + _meta: { + ...request.params?._meta, + progressToken: messageId + } + }; + } + const outbound = this._envelopeOutbound(jsonrpcRequest); + let responseReceived = false; + const cancel = (reason) => { + if (responseReceived) return; + this._progressHandlers.delete(messageId); + if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ + jsonrpc: "2.0", + method: "notifications/cancelled", + params: { + requestId: messageId, + reason: String(reason) + } + }), { + relatedRequestId, + resumptionToken, + onresumptiontoken + }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); + else requestAbort.abort(); + reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); + }; + this._responseHandlers.set(messageId, (response) => { + if (options?.signal?.aborted) return; + responseReceived = true; + if (response instanceof Error) return reject(response); + let decoded; + try { + decoded = codec.decodeResult(request.method, response.result); + } catch (error) { + return reject(error instanceof Error ? error : new Error(String(error))); + } + if (decoded.kind === "invalid") return reject(decoded.error); + if (decoded.kind === "input_required") { + if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); + const flow = { + codec, + request, + resultSchema, + options, + flowStartedAt, + retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { + method: request.method, + params + }, resultSchema, legOptions) + }; + return resolve(this._resolveNonCompleteResult(decoded, flow)); + } + const result = decoded.result; + validateStandardSchema(resultSchema, result).then((parseResult) => { + if (parseResult.success) resolve(parseResult.data); + else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); + }, reject); + }); + onAbort = () => cancel(options?.signal?.reason); + options?.signal?.addEventListener("abort", onAbort, { once: true }); + const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; + const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); + this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); + this._transport.send(outbound, { + relatedRequestId, + resumptionToken, + onresumptiontoken, + headers, + requestSignal: requestAbort?.signal + }).catch((error) => { + this._progressHandlers.delete(messageId); + reject(error); + }); + }).finally(() => { + if (onAbort) options?.signal?.removeEventListener("abort", onAbort); + if (cleanupMessageId !== void 0) { + this._responseHandlers.delete(cleanupMessageId); + this._cleanupTimeout(cleanupMessageId); + } + }); + } + /** + * Emits a notification, which is a one-way message that does not expect a response. + */ + async notification(notification, options) { + return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); + } + /** + * The notification funnel proper, keyed by the resolved era codec — + * direct sends and related notifications (`ctx.mcpReq.notify`) alike + * resolve through the instance's negotiated era at send time. + */ + async _notificationViaCodec(codec, notification, options) { + if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { + method: notification.method, + era: codec.era + }); + this.assertNotificationCapability(notification.method); + const jsonrpcNotification = this._envelopeOutbound({ + jsonrpc: "2.0", + ...notification + }); + if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { + if (this._pendingDebouncedNotifications.has(notification.method)) return; + this._pendingDebouncedNotifications.add(notification.method); + Promise.resolve().then(() => { + this._pendingDebouncedNotifications.delete(notification.method); + if (!this._transport) return; + this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); + }); + return; + } + await this._transport.send(jsonrpcNotification, options); + } + setRequestHandler(method, schemasOrHandler, maybeHandler) { + this.assertRequestHandlerCapability(method); + let stored; + if (typeof schemasOrHandler === "function") { + if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); + stored = (request, ctx) => { + const dispatchCodec = this._negotiatedWireCodec(); + let outcome = dispatchCodec.validateRequest(method, request); + if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value, ctx)); + }; + } else if (maybeHandler) stored = async (request, ctx) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); + return maybeHandler(parsed.data, ctx); + }; + else throw new TypeError("setRequestHandler: handler is required"); + this._requestHandlers.set(method, this._wrapHandler(method, stored)); + } + /** + * Hook for subclasses to wrap a registered request handler with role-specific + * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` + * validates `elicitation/create` mode and result). Runs for both the 2-arg and + * 3-arg registration paths. The default implementation is identity. + * + * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. + */ + _wrapHandler(_method, handler) { + return handler; + } + /** + * Hook for subclasses to supply the implementation identity the 2026-era + * encode seam stamps into outbound result `_meta` under + * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD + * identify themselves on every response). The default is `undefined` — no + * stamp. Only `Server` overrides this: the key identifies the software + * producing a response, and the 2025-era codec never stamps anything + * regardless (the never-stamp guarantee). + */ + _outboundServerInfo() {} + /** + * Removes the request handler for the given method. + */ + removeRequestHandler(method) { + this._requestHandlers.delete(method); + } + /** + * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. + */ + assertCanSetRequestHandler(method) { + if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); + } + setNotificationHandler(method, schemasOrHandler, maybeHandler) { + if (typeof schemasOrHandler === "function") { + if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); + this._notificationHandlers.set(method, (notification, codec) => { + const outcome = codec.validateNotification(method, notification); + if (!outcome.ok) { + if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); + throw new Error(outcome.message); + } + return Promise.resolve(schemasOrHandler(outcome.value)); + }); + return; + } + if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); + this._notificationHandlers.set(method, async (notification) => { + const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); + if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); + await maybeHandler(parsed.data, notification); + }); + } + /** + * Removes the notification handler for the given method. + */ + removeNotificationHandler(method) { + this._notificationHandlers.delete(method); + } +}; +function isPlainObject$1(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} +function mergeCapabilities(base, additional) { + const result = { ...base }; + for (const key in additional) { + const k = key; + const addValue = additional[k]; + if (addValue === void 0) continue; + const baseValue = result[k]; + result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { + ...baseValue, + ...addValue + } : addValue; + } + return result; +} + +//#endregion +//#region ../core-internal/src/shared/inputRequiredEngine.ts +function src_CX2iR2pK_isPlainObject(value) { + return typeof value === "object" && value !== null && !Array.isArray(value); +} +/** +* Splits a retried request's `inputResponses` map into the BARE response +* entries the spec defines and everything else. The spec's embedded responses +* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or +* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some +* peers emit) is never accepted as a response — its key is recorded so the +* handler can re-issue the corresponding input request. +*/ +function partitionInputResponses(inputResponses) { + const accepted = {}; + const droppedKeys = []; + if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { + accepted, + droppedKeys + }; + for (const [key, entry] of Object.entries(inputResponses)) { + if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { + droppedKeys.push(key); + continue; + } + accepted[key] = entry; + } + return { + accepted, + droppedKeys + }; +} +/** +* Builds the manual-mode {@linkcode InputRequiredResult} value from the +* codec's decoded payload — what an `allowInputRequired: true` caller +* receives instead of the auto-fulfilled complete result. +*/ +function manualInputRequiredValue(decoded) { + return { + resultType: "input_required", + inputRequests: decoded.inputRequests, + ...decoded.requestState !== void 0 && { requestState: decoded.requestState } + }; +} + +//#endregion +//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js +/*! +* content-type +* Copyright(c) 2015 Douglas Christopher Wilson +* MIT Licensed +*/ +var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { + /** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ + var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; + /** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ + var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; + /** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ + var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; + exports.parse = parse; + /** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + function parse(string) { + if (!string) throw new TypeError("argument string is required"); + var header = typeof string === "object" ? getcontenttype(string) : string; + if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); + var index = header.indexOf(";"); + var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); + if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); + var obj = new ContentType(type.toLowerCase()); + if (index !== -1) { + var key; + var match; + var value; + PARAM_REGEXP.lastIndex = index; + while (match = PARAM_REGEXP.exec(header)) { + if (match.index !== index) throw new TypeError("invalid parameter format"); + index += match[0].length; + key = match[1].toLowerCase(); + value = match[2]; + if (value.charCodeAt(0) === 34) { + value = value.slice(1, -1); + if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); + } + obj.parameters[key] = value; + } + if (index !== header.length) throw new TypeError("invalid parameter format"); + } + return obj; + } + /** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + function getcontenttype(obj) { + var header; + if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); + else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; + if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); + return header; + } + /** + * Class to represent a content type. + * @private + */ + function ContentType(type) { + this.parameters = Object.create(null); + this.type = type; + } +})); + +//#endregion +//#region ../core-internal/src/shared/mediaType.ts +var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); +/** +* Extracts the media type (the lowercased `type/subtype` pair, without +* parameters) from a raw `Content-Type` header value, or `undefined` when the +* header is missing or empty. +* +* Content-Type comparisons must use the parsed media type, never a substring +* search of the raw header: a value like `text/plain; a=application/json` +* contains the substring `application/json` but its media type is +* `text/plain`, and case variants or parameters make naive string comparison +* wrong in both directions. +* +* "Essence" is the WHATWG MIME Sniffing standard's term for the bare +* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); +* the Fetch standard's request classification is defined against it +* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). +* +* Parsing is RFC 9110 (`content-type` package) first. When the parameter +* section is malformed (`application/json;`, `application/json; charset=`), +* browsers and most HTTP stacks still derive the media type from the segment +* before the first `;` — the fallback matches that widely-implemented +* behavior, so a header whose media type is unambiguous is not rejected for +* a sloppy parameter section. +*/ +function src_CX2iR2pK_mediaTypeEssence(header) { + if (!header) return; + try { + return import_content_type.parse(header).type; + } catch { + const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); + if (essence === "" || header.slice(essence.length).includes(",")) return; + return essence; + } +} +/** +* Whether a raw `Content-Type` header value denotes `application/json`. +* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed +* parameter sections do not reject a header whose media type is unambiguously +* `application/json` (see `mediaTypeEssence` for the exact grammar). +*/ +function src_CX2iR2pK_isJsonContentType(header) { + if (header === "application/json") return true; + return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; +} + +//#endregion +//#region ../core-internal/src/shared/metadataUtils.ts +/** +* Utilities for working with {@linkcode BaseMetadata} objects. +*/ +/** +* Gets the display name for an object with {@linkcode BaseMetadata}. +* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` +* For other objects: `title` → `name` +* This implements the spec requirement: "if no title is provided, name should be used for display purposes" +*/ +function getDisplayName(metadata) { + if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; + if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; + return metadata.name; +} + +//#endregion +//#region ../core-internal/src/shared/stdio.ts +const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; +/** +* Buffers a continuous stdio stream into discrete JSON-RPC messages. +*/ +var ReadBuffer = class { + _buffer; + _maxBufferSize; + constructor(options) { + this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; + } + append(chunk) { + if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { + this.clear(); + throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); + } + this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; + } + readMessage() { + while (this._buffer) { + const index = this._buffer.indexOf("\n"); + if (index === -1) return null; + const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); + this._buffer = this._buffer.subarray(index + 1); + try { + return deserializeMessage(line); + } catch (error) { + if (error instanceof SyntaxError) continue; + throw error; + } + } + return null; + } + clear() { + this._buffer = void 0; + } +}; +function deserializeMessage(line) { + return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); +} +function serializeMessage(message) { + return JSON.stringify(message) + "\n"; +} + +//#endregion +//#region ../core-internal/src/shared/toolNameValidation.ts +/** +* Tool name validation utilities according to SEP: Specify Format for Tool Names +* +* Tool names SHOULD be between 1 and 128 characters in length (inclusive). +* Tool names are case-sensitive. +* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits +* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). +* Tool names SHOULD NOT contain spaces, commas, or other special characters. +* +* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} +*/ +/** +* Regular expression for valid tool names according to SEP-986 specification +*/ +const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; +/** +* Validates a tool name according to the SEP specification +* @param name - The tool name to validate +* @returns An object containing validation result and any warnings +*/ +function validateToolName(name) { + const warnings = []; + if (name.length === 0) return { + isValid: false, + warnings: ["Tool name cannot be empty"] + }; + if (name.length > 128) return { + isValid: false, + warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] + }; + if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); + if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); + if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); + if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); + if (!TOOL_NAME_REGEX.test(name)) { + const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); + warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); + return { + isValid: false, + warnings + }; + } + return { + isValid: true, + warnings + }; +} +/** +* Issues warnings for non-conforming tool names +* @param name - The tool name that triggered the warnings +* @param warnings - Array of warning messages +*/ +function issueToolNameWarning(name, warnings) { + if (warnings.length > 0) { + console.warn(`Tool name validation warning for "${name}":`); + for (const warning of warnings) console.warn(` - ${warning}`); + console.warn("Tool registration will proceed, but this may cause compatibility issues."); + console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); + console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); + } +} +/** +* Validates a tool name and issues warnings for non-conforming names +* @param name - The tool name to validate +* @returns `true` if the name is valid, `false` otherwise +*/ +function validateAndWarnToolName(name) { + const result = validateToolName(name); + issueToolNameWarning(name, result.warnings); + return result.isValid; +} + +//#endregion +//#region ../core-internal/src/shared/transport.ts +/** +* Normalizes `HeadersInit` to a plain `Record` for manipulation. +* Handles `Headers` objects, arrays of tuples, and plain objects. +*/ +function normalizeHeaders(headers) { + if (!headers) return {}; + if (headers instanceof Headers) return Object.fromEntries(headers.entries()); + if (Array.isArray(headers)) return Object.fromEntries(headers); + return { ...headers }; +} +/** +* Creates a fetch function that includes base `RequestInit` options. +* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. +* +* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) +* @param baseInit - The base `RequestInit` to merge with each request +* @returns A wrapped fetch function that merges base options with call-specific options +*/ +function createFetchWithInit(baseFetch = fetch, baseInit) { + if (!baseInit) return baseFetch; + return async (url, init) => { + return baseFetch(url, { + ...baseInit, + ...init, + headers: init?.headers ? { + ...normalizeHeaders(baseInit.headers), + ...normalizeHeaders(init.headers) + } : baseInit.headers + }); + }; +} + +//#endregion +//#region ../core-internal/src/shared/uriTemplate.ts +const MAX_TEMPLATE_LENGTH = 1e6; +const MAX_VARIABLE_LENGTH = 1e6; +const MAX_TEMPLATE_EXPRESSIONS = 1e4; +const MAX_REGEX_LENGTH = 1e6; +var src_CX2iR2pK_UriTemplate = class UriTemplate { + /** + * Returns true if the given string contains any URI template expressions. + * A template expression is a sequence of characters enclosed in curly braces, + * like `{foo}` or `{?bar}`. + */ + static isTemplate(str) { + return /\{[^}\s]+\}/.test(str); + } + static validateLength(str, max, context) { + if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); + } + template; + parts; + get variableNames() { + return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); + } + constructor(template) { + UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); + this.template = template; + this.parts = this.parse(template); + } + toString() { + return this.template; + } + parse(template) { + const parts = []; + let currentText = ""; + let i = 0; + let expressionCount = 0; + while (i < template.length) if (template[i] === "{") { + if (currentText) { + parts.push(currentText); + currentText = ""; + } + const end = template.indexOf("}", i); + if (end === -1) throw new Error("Unclosed template expression"); + expressionCount++; + if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); + const expr = template.slice(i + 1, end); + const operator = this.getOperator(expr); + const exploded = expr.includes("*"); + const names = this.getNames(expr); + const name = names[0]; + for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + parts.push({ + name, + operator, + names, + exploded + }); + i = end + 1; + } else { + currentText += template[i]; + i++; + } + if (currentText) parts.push(currentText); + return parts; + } + getOperator(expr) { + return [ + "+", + "#", + ".", + "/", + "?", + "&" + ].find((op) => expr.startsWith(op)) || ""; + } + getNames(expr) { + const operator = this.getOperator(expr); + return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); + } + encodeValue(value, operator) { + UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); + if (operator === "+" || operator === "#") return encodeURI(value); + return encodeURIComponent(value); + } + expandPart(part, variables) { + if (part.operator === "?" || part.operator === "&") { + const pairs = part.names.map((name) => { + const value$1 = variables[name]; + if (value$1 === void 0) return ""; + return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; + }).filter((pair) => pair.length > 0); + if (pairs.length === 0) return ""; + return (part.operator === "?" ? "?" : "&") + pairs.join("&"); + } + if (part.names.length > 1) { + const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); + if (values.length === 0) return ""; + return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); + } + const value = variables[part.name]; + if (value === void 0) return ""; + const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); + switch (part.operator) { + case "": return encoded.join(","); + case "+": return encoded.join(","); + case "#": return "#" + encoded.join(","); + case ".": return "." + encoded.join("."); + case "/": return "/" + encoded.join("/"); + default: return encoded.join(","); + } + } + expand(variables) { + let result = ""; + let hasQueryParam = false; + for (const part of this.parts) { + if (typeof part === "string") { + result += part; + continue; + } + const expanded = this.expandPart(part, variables); + if (!expanded) continue; + result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; + if (part.operator === "?" || part.operator === "&") hasQueryParam = true; + } + return result; + } + escapeRegExp(str) { + return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); + } + partToRegExp(part) { + const patterns = []; + for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); + if (part.operator === "?" || part.operator === "&") { + for (let i = 0; i < part.names.length; i++) { + const name$1 = part.names[i]; + const prefix = i === 0 ? "\\" + part.operator : "&"; + patterns.push({ + pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", + name: name$1 + }); + } + return patterns; + } + let pattern; + const name = part.name; + switch (part.operator) { + case "": + pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; + break; + case "+": + case "#": + pattern = "(.+)"; + break; + case ".": + pattern = String.raw`\.([^/,]+)`; + break; + case "/": + pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); + break; + default: pattern = "([^/]+)"; + } + patterns.push({ + pattern, + name + }); + return patterns; + } + match(uri) { + UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); + let pattern = "^"; + const names = []; + for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); + else { + const patterns = this.partToRegExp(part); + for (const { pattern: partPattern, name } of patterns) { + pattern += partPattern; + names.push({ + name, + exploded: part.exploded + }); + } + } + pattern += "$"; + UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); + const regex = new RegExp(pattern); + const match = uri.match(regex); + if (!match) return null; + const result = {}; + for (const [i, name_] of names.entries()) { + const { name, exploded } = name_; + const value = match[i + 1]; + const cleanName = name.replace("*", ""); + result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; + } + return result; + } +}; + +//#endregion +//#region ../core-internal/src/util/inMemory.ts +/** +* In-memory transport for creating clients and servers that talk to each other within the same process. +* +* Intended for testing and development. For production in-process connections, use +* `StreamableHTTPClientTransport` against a local server URL. +*/ +var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { + _otherTransport; + _messageQueue = []; + _closed = false; + onclose; + onerror; + onmessage; + sessionId; + /** + * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. + */ + static createLinkedPair() { + const clientTransport = new InMemoryTransport(); + const serverTransport = new InMemoryTransport(); + clientTransport._otherTransport = serverTransport; + serverTransport._otherTransport = clientTransport; + return [clientTransport, serverTransport]; + } + async start() { + while (this._messageQueue.length > 0) { + const queuedMessage = this._messageQueue.shift(); + this.onmessage?.(queuedMessage.message, queuedMessage.extra); + } + } + async close() { + if (this._closed) return; + this._closed = true; + const other = this._otherTransport; + this._otherTransport = void 0; + try { + await other?.close(); + } finally { + this.onclose?.(); + } + } + /** + * Sends a message with optional auth info. + * This is useful for testing authentication scenarios. + */ + async send(message, options) { + if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); + if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); + else this._otherTransport._messageQueue.push({ + message, + extra: { authInfo: options?.authInfo } + }); + } +}; + +//#endregion +//#region ../core-internal/src/util/zodCompat.ts +/** +* Zod-specific helpers for the v1-compat raw-shape shorthand on +* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so +* that file stays library-agnostic per the Standard Schema spec. +*/ +function isZodV4Schema(v) { + return typeof v === "object" && v !== null && "_zod" in v; +} +function looksLikeZodV3(v) { + return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; +} +/** +* Detects a "raw shape" — a plain object whose values are Zod field schemas, +* e.g. `{ name: z.string() }`. Powers the auto-wrap in +* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only +* Zod values are supported. +* +* @internal +*/ +function isZodRawShape(obj) { + if (typeof obj !== "object" || obj === null) return false; + if (isStandardSchema(obj)) return false; + const proto = Object.getPrototypeOf(obj); + if (proto !== Object.prototype && proto !== null) return false; + return Object.values(obj).every((v) => isZodV4Schema(v)); +} +/** +* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape +* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. +* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a +* uniform schema type; already-wrapped schemas pass through unchanged. +* +* @internal +*/ +function normalizeRawShapeSchema(schema) { + if (schema === void 0) return void 0; + if (isZodRawShape(schema)) return schemas_object(schema); + if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); + if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); + return schema; +} + +//#endregion +//#region ../core-internal/src/wire/preload.ts +/** +* Explicit warm-up entry for the lazy wire-schema layers. +* +* The per-revision wire schemas are built lazily: each era's schema set sits +* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the +* registry/codec lookup maps above those factories are memoized the same way. +* That laziness is the right default on process-per-invocation runtimes (CLI +* tools, dev servers), where module evaluation IS startup latency and most +* short-lived processes never validate a message on both eras. +* +* On platforms that bill request CPU but not module evaluation — isolate-based +* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: +* module-scope work runs during isolate warm-up outside any request, while +* lazy construction lands inside the first request's billed (and latency +* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move +* the one-time construction cost back to module scope by calling it at module +* scope themselves. The packages' own workerd shims already do this, so +* Workers deployments get eager construction automatically. +*/ +/** +* Eagerly builds every lazily-constructed wire-schema layer, so that no later +* validation pays schema-construction cost. +* +* Synchronous and idempotent: every layer is a memo, so the first call does +* all the work and subsequent calls return immediately. Reference identity is +* unaffected — this forces the same memos every lazy consumer pulls through. +* +* Call it at module scope on platforms that bill per-request CPU but not +* module evaluation (isolate-based edge/serverless runtimes), where deferring +* construction would move it into the first request of every fresh isolate: +* +* ```ts +* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — +* // each package bundles its own schema copy, so warm the one(s) you import. +* preloadSchemas(); // module scope — runs during isolate warm-up +* ``` +* +* On Node CLIs and other process-per-invocation runtimes, prefer the lazy +* default — there, module-scope construction is pure added boot latency. +*/ +function preloadSchemas() { + buildSchemas2025(); + buildSchemas2026(); + warmRegistryMaps2025(); + warmInputSchemaMaps2026(); + warmWireResultSchemas2026(); +} + +//#endregion +//#region ../core-internal/src/validators/fromJsonSchema.ts +/** +* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be +* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON +* Schema (e.g. from TypeBox, or hand-written) and want to register it without going +* through a Standard Schema library. +* +* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript +* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. +* +* @param schema - A JSON Schema object describing the expected shape +* @param validator - A validator provider. When importing `fromJsonSchema` from +* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate +* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). +* +* @example +* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" +* const inputSchema = fromJsonSchema<{ name: string }>( +* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, +* validator +* ); +* // Use with server.registerTool('greet', { inputSchema }, handler) +* ``` +*/ +function fromJsonSchema(schema, validator) { + const check = validator.getValidator(schema); + return { "~standard": { + version: 1, + vendor: "mcp", + jsonSchema: { + input: () => schema, + output: () => schema + }, + validate: (data) => { + const result = check(data); + return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; + } + } }; +} + +//#endregion + +//# sourceMappingURL=src-CX2iR2pK.mjs.map + + + +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js +var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; + var _CodeOrName = class {}; + exports._CodeOrName = _CodeOrName; + exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; + var Name = class extends _CodeOrName { + constructor(s) { + super(); + if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); + this.str = s; + } + toString() { + return this.str; + } + emptyStr() { + return false; + } + get names() { + return { [this.str]: 1 }; + } + }; + exports.Name = Name; + var _Code = class extends _CodeOrName { + constructor(code) { + super(); + this._items = typeof code === "string" ? [code] : code; + } + toString() { + return this.str; + } + emptyStr() { + if (this._items.length > 1) return false; + const item = this._items[0]; + return item === "" || item === "\"\""; + } + get str() { + var _a; + return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); + } + get names() { + var _a; + return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { + if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; + return names; + }, {}); + } + }; + exports._Code = _Code; + exports.nil = new _Code(""); + function _(strs, ...args) { + const code = [strs[0]]; + let i = 0; + while (i < args.length) { + addCodeArg(code, args[i]); + code.push(strs[++i]); + } + return new _Code(code); + } + exports._ = _; + const plus = new _Code("+"); + function str(strs, ...args) { + const expr = [safeStringify(strs[0])]; + let i = 0; + while (i < args.length) { + expr.push(plus); + addCodeArg(expr, args[i]); + expr.push(plus, safeStringify(strs[++i])); + } + optimize(expr); + return new _Code(expr); + } + exports.str = str; + function addCodeArg(code, arg) { + if (arg instanceof _Code) code.push(...arg._items); + else if (arg instanceof Name) code.push(arg); + else code.push(interpolate(arg)); + } + exports.addCodeArg = addCodeArg; + function optimize(expr) { + let i = 1; + while (i < expr.length - 1) { + if (expr[i] === plus) { + const res = mergeExprItems(expr[i - 1], expr[i + 1]); + if (res !== void 0) { + expr.splice(i - 1, 3, res); + continue; + } + expr[i++] = "+"; + } + i++; + } + } + function mergeExprItems(a, b) { + if (b === "\"\"") return a; + if (a === "\"\"") return b; + if (typeof a == "string") { + if (b instanceof Name || a[a.length - 1] !== "\"") return; + if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; + if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); + return; + } + if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; + } + function strConcat(c1, c2) { + return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; + } + exports.strConcat = strConcat; + function interpolate(x) { + return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); + } + function stringify(x) { + return new _Code(safeStringify(x)); + } + exports.stringify = stringify; + function safeStringify(x) { + return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); + } + exports.safeStringify = safeStringify; + function getProperty(key) { + return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; + } + exports.getProperty = getProperty; + function getEsmExportName(key) { + if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); + throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); + } + exports.getEsmExportName = getEsmExportName; + function regexpCode(rx) { + return new _Code(rx.toString()); + } + exports.regexpCode = regexpCode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js +var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; + const code_1 = require_code$1(); + var ValueError = class extends Error { + constructor(name) { + super(`CodeGen: "code" for ${name} not defined`); + this.value = name.value; + } + }; + var UsedValueState; + (function(UsedValueState) { + UsedValueState[UsedValueState["Started"] = 0] = "Started"; + UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; + })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); + exports.varKinds = { + const: new code_1.Name("const"), + let: new code_1.Name("let"), + var: new code_1.Name("var") + }; + var Scope = class { + constructor({ prefixes, parent } = {}) { + this._names = {}; + this._prefixes = prefixes; + this._parent = parent; + } + toName(nameOrPrefix) { + return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); + } + name(prefix) { + return new code_1.Name(this._newName(prefix)); + } + _newName(prefix) { + const ng = this._names[prefix] || this._nameGroup(prefix); + return `${prefix}${ng.index++}`; + } + _nameGroup(prefix) { + var _a, _b; + if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); + return this._names[prefix] = { + prefix, + index: 0 + }; + } + }; + exports.Scope = Scope; + var ValueScopeName = class extends code_1.Name { + constructor(prefix, nameStr) { + super(nameStr); + this.prefix = prefix; + } + setValue(value, { property, itemIndex }) { + this.value = value; + this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; + } + }; + exports.ValueScopeName = ValueScopeName; + const line = (0, code_1._)`\n`; + var ValueScope = class extends Scope { + constructor(opts) { + super(opts); + this._values = {}; + this._scope = opts.scope; + this.opts = { + ...opts, + _n: opts.lines ? line : code_1.nil + }; + } + get() { + return this._scope; + } + name(prefix) { + return new ValueScopeName(prefix, this._newName(prefix)); + } + value(nameOrPrefix, value) { + var _a; + if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); + const name = this.toName(nameOrPrefix); + const { prefix } = name; + const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; + let vs = this._values[prefix]; + if (vs) { + const _name = vs.get(valueKey); + if (_name) return _name; + } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); + vs.set(valueKey, name); + const s = this._scope[prefix] || (this._scope[prefix] = []); + const itemIndex = s.length; + s[itemIndex] = value.ref; + name.setValue(value, { + property: prefix, + itemIndex + }); + return name; + } + getValue(prefix, keyOrRef) { + const vs = this._values[prefix]; + if (!vs) return; + return vs.get(keyOrRef); + } + scopeRefs(scopeName, values = this._values) { + return this._reduceValues(values, (name) => { + if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return (0, code_1._)`${scopeName}${name.scopePath}`; + }); + } + scopeCode(values = this._values, usedValues, getCode) { + return this._reduceValues(values, (name) => { + if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); + return name.value.code; + }, usedValues, getCode); + } + _reduceValues(values, valueCode, usedValues = {}, getCode) { + let code = code_1.nil; + for (const prefix in values) { + const vs = values[prefix]; + if (!vs) continue; + const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); + vs.forEach((name) => { + if (nameSet.has(name)) return; + nameSet.set(name, UsedValueState.Started); + let c = valueCode(name); + if (c) { + const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; + code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; + } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; + else throw new ValueError(name); + nameSet.set(name, UsedValueState.Completed); + }); + } + return code; + } + }; + exports.ValueScope = ValueScope; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js +var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; + const code_1 = require_code$1(); + const scope_1 = require_scope(); + var code_2 = require_code$1(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return code_2._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return code_2.str; + } + }); + Object.defineProperty(exports, "strConcat", { + enumerable: true, + get: function() { + return code_2.strConcat; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return code_2.nil; + } + }); + Object.defineProperty(exports, "getProperty", { + enumerable: true, + get: function() { + return code_2.getProperty; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return code_2.stringify; + } + }); + Object.defineProperty(exports, "regexpCode", { + enumerable: true, + get: function() { + return code_2.regexpCode; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return code_2.Name; + } + }); + var scope_2 = require_scope(); + Object.defineProperty(exports, "Scope", { + enumerable: true, + get: function() { + return scope_2.Scope; + } + }); + Object.defineProperty(exports, "ValueScope", { + enumerable: true, + get: function() { + return scope_2.ValueScope; + } + }); + Object.defineProperty(exports, "ValueScopeName", { + enumerable: true, + get: function() { + return scope_2.ValueScopeName; + } + }); + Object.defineProperty(exports, "varKinds", { + enumerable: true, + get: function() { + return scope_2.varKinds; + } + }); + exports.operators = { + GT: new code_1._Code(">"), + GTE: new code_1._Code(">="), + LT: new code_1._Code("<"), + LTE: new code_1._Code("<="), + EQ: new code_1._Code("==="), + NEQ: new code_1._Code("!=="), + NOT: new code_1._Code("!"), + OR: new code_1._Code("||"), + AND: new code_1._Code("&&"), + ADD: new code_1._Code("+") + }; + var Node = class { + optimizeNodes() { + return this; + } + optimizeNames(_names, _constants) { + return this; + } + }; + var Def = class extends Node { + constructor(varKind, name, rhs) { + super(); + this.varKind = varKind; + this.name = name; + this.rhs = rhs; + } + render({ es5, _n }) { + const varKind = es5 ? scope_1.varKinds.var : this.varKind; + const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; + return `${varKind} ${this.name}${rhs};` + _n; + } + optimizeNames(names, constants) { + if (!names[this.name.str]) return; + if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; + } + }; + var Assign = class extends Node { + constructor(lhs, rhs, sideEffects) { + super(); + this.lhs = lhs; + this.rhs = rhs; + this.sideEffects = sideEffects; + } + render({ _n }) { + return `${this.lhs} = ${this.rhs};` + _n; + } + optimizeNames(names, constants) { + if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; + this.rhs = optimizeExpr(this.rhs, names, constants); + return this; + } + get names() { + return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); + } + }; + var AssignOp = class extends Assign { + constructor(lhs, op, rhs, sideEffects) { + super(lhs, rhs, sideEffects); + this.op = op; + } + render({ _n }) { + return `${this.lhs} ${this.op}= ${this.rhs};` + _n; + } + }; + var Label = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `${this.label}:` + _n; + } + }; + var Break = class extends Node { + constructor(label) { + super(); + this.label = label; + this.names = {}; + } + render({ _n }) { + return `break${this.label ? ` ${this.label}` : ""};` + _n; + } + }; + var Throw = class extends Node { + constructor(error) { + super(); + this.error = error; + } + render({ _n }) { + return `throw ${this.error};` + _n; + } + get names() { + return this.error.names; + } + }; + var AnyCode = class extends Node { + constructor(code) { + super(); + this.code = code; + } + render({ _n }) { + return `${this.code};` + _n; + } + optimizeNodes() { + return `${this.code}` ? this : void 0; + } + optimizeNames(names, constants) { + this.code = optimizeExpr(this.code, names, constants); + return this; + } + get names() { + return this.code instanceof code_1._CodeOrName ? this.code.names : {}; + } + }; + var ParentNode = class extends Node { + constructor(nodes = []) { + super(); + this.nodes = nodes; + } + render(opts) { + return this.nodes.reduce((code, n) => code + n.render(opts), ""); + } + optimizeNodes() { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i].optimizeNodes(); + if (Array.isArray(n)) nodes.splice(i, 1, ...n); + else if (n) nodes[i] = n; + else nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + optimizeNames(names, constants) { + const { nodes } = this; + let i = nodes.length; + while (i--) { + const n = nodes[i]; + if (n.optimizeNames(names, constants)) continue; + subtractNames(names, n.names); + nodes.splice(i, 1); + } + return nodes.length > 0 ? this : void 0; + } + get names() { + return this.nodes.reduce((names, n) => addNames(names, n.names), {}); + } + }; + var BlockNode = class extends ParentNode { + render(opts) { + return "{" + opts._n + super.render(opts) + "}" + opts._n; + } + }; + var Root = class extends ParentNode {}; + var Else = class extends BlockNode {}; + Else.kind = "else"; + var If = class If extends BlockNode { + constructor(condition, nodes) { + super(nodes); + this.condition = condition; + } + render(opts) { + let code = `if(${this.condition})` + super.render(opts); + if (this.else) code += "else " + this.else.render(opts); + return code; + } + optimizeNodes() { + super.optimizeNodes(); + const cond = this.condition; + if (cond === true) return this.nodes; + let e = this.else; + if (e) { + const ns = e.optimizeNodes(); + e = this.else = Array.isArray(ns) ? new Else(ns) : ns; + } + if (e) { + if (cond === false) return e instanceof If ? e : e.nodes; + if (this.nodes.length) return this; + return new If(not(cond), e instanceof If ? [e] : e.nodes); + } + if (cond === false || !this.nodes.length) return void 0; + return this; + } + optimizeNames(names, constants) { + var _a; + this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); + if (!(super.optimizeNames(names, constants) || this.else)) return; + this.condition = optimizeExpr(this.condition, names, constants); + return this; + } + get names() { + const names = super.names; + addExprNames(names, this.condition); + if (this.else) addNames(names, this.else.names); + return names; + } + }; + If.kind = "if"; + var For = class extends BlockNode {}; + For.kind = "for"; + var ForLoop = class extends For { + constructor(iteration) { + super(); + this.iteration = iteration; + } + render(opts) { + return `for(${this.iteration})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iteration = optimizeExpr(this.iteration, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iteration.names); + } + }; + var ForRange = class extends For { + constructor(varKind, name, from, to) { + super(); + this.varKind = varKind; + this.name = name; + this.from = from; + this.to = to; + } + render(opts) { + const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; + const { name, from, to } = this; + return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); + } + get names() { + return addExprNames(addExprNames(super.names, this.from), this.to); + } + }; + var ForIter = class extends For { + constructor(loop, varKind, name, iterable) { + super(); + this.loop = loop; + this.varKind = varKind; + this.name = name; + this.iterable = iterable; + } + render(opts) { + return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); + } + optimizeNames(names, constants) { + if (!super.optimizeNames(names, constants)) return; + this.iterable = optimizeExpr(this.iterable, names, constants); + return this; + } + get names() { + return addNames(super.names, this.iterable.names); + } + }; + var Func = class extends BlockNode { + constructor(name, args, async) { + super(); + this.name = name; + this.args = args; + this.async = async; + } + render(opts) { + return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); + } + }; + Func.kind = "func"; + var Return = class extends ParentNode { + render(opts) { + return "return " + super.render(opts); + } + }; + Return.kind = "return"; + var Try = class extends BlockNode { + render(opts) { + let code = "try" + super.render(opts); + if (this.catch) code += this.catch.render(opts); + if (this.finally) code += this.finally.render(opts); + return code; + } + optimizeNodes() { + var _a, _b; + super.optimizeNodes(); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); + return this; + } + optimizeNames(names, constants) { + var _a, _b; + super.optimizeNames(names, constants); + (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); + (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); + return this; + } + get names() { + const names = super.names; + if (this.catch) addNames(names, this.catch.names); + if (this.finally) addNames(names, this.finally.names); + return names; + } + }; + var Catch = class extends BlockNode { + constructor(error) { + super(); + this.error = error; + } + render(opts) { + return `catch(${this.error})` + super.render(opts); + } + }; + Catch.kind = "catch"; + var Finally = class extends BlockNode { + render(opts) { + return "finally" + super.render(opts); + } + }; + Finally.kind = "finally"; + var CodeGen = class { + constructor(extScope, opts = {}) { + this._values = {}; + this._blockStarts = []; + this._constants = {}; + this.opts = { + ...opts, + _n: opts.lines ? "\n" : "" + }; + this._extScope = extScope; + this._scope = new scope_1.Scope({ parent: extScope }); + this._nodes = [new Root()]; + } + toString() { + return this._root.render(this.opts); + } + name(prefix) { + return this._scope.name(prefix); + } + scopeName(prefix) { + return this._extScope.name(prefix); + } + scopeValue(prefixOrName, value) { + const name = this._extScope.value(prefixOrName, value); + (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); + return name; + } + getScopeValue(prefix, keyOrRef) { + return this._extScope.getValue(prefix, keyOrRef); + } + scopeRefs(scopeName) { + return this._extScope.scopeRefs(scopeName, this._values); + } + scopeCode() { + return this._extScope.scopeCode(this._values); + } + _def(varKind, nameOrPrefix, rhs, constant) { + const name = this._scope.toName(nameOrPrefix); + if (rhs !== void 0 && constant) this._constants[name.str] = rhs; + this._leafNode(new Def(varKind, name, rhs)); + return name; + } + const(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); + } + let(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); + } + var(nameOrPrefix, rhs, _constant) { + return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); + } + assign(lhs, rhs, sideEffects) { + return this._leafNode(new Assign(lhs, rhs, sideEffects)); + } + add(lhs, rhs) { + return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); + } + code(c) { + if (typeof c == "function") c(); + else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); + return this; + } + object(...keyValues) { + const code = ["{"]; + for (const [key, value] of keyValues) { + if (code.length > 1) code.push(","); + code.push(key); + if (key !== value || this.opts.es5) { + code.push(":"); + (0, code_1.addCodeArg)(code, value); + } + } + code.push("}"); + return new code_1._Code(code); + } + if(condition, thenBody, elseBody) { + this._blockNode(new If(condition)); + if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); + else if (thenBody) this.code(thenBody).endIf(); + else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); + return this; + } + elseIf(condition) { + return this._elseNode(new If(condition)); + } + else() { + return this._elseNode(new Else()); + } + endIf() { + return this._endBlockNode(If, Else); + } + _for(node, forBody) { + this._blockNode(node); + if (forBody) this.code(forBody).endFor(); + return this; + } + for(iteration, forBody) { + return this._for(new ForLoop(iteration), forBody); + } + forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); + } + forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { + const name = this._scope.toName(nameOrPrefix); + if (this.opts.es5) { + const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); + return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { + this.var(name, (0, code_1._)`${arr}[${i}]`); + forBody(name); + }); + } + return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); + } + forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { + if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); + const name = this._scope.toName(nameOrPrefix); + return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); + } + endFor() { + return this._endBlockNode(For); + } + label(label) { + return this._leafNode(new Label(label)); + } + break(label) { + return this._leafNode(new Break(label)); + } + return(value) { + const node = new Return(); + this._blockNode(node); + this.code(value); + if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); + return this._endBlockNode(Return); + } + try(tryBody, catchCode, finallyCode) { + if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); + const node = new Try(); + this._blockNode(node); + this.code(tryBody); + if (catchCode) { + const error = this.name("e"); + this._currNode = node.catch = new Catch(error); + catchCode(error); + } + if (finallyCode) { + this._currNode = node.finally = new Finally(); + this.code(finallyCode); + } + return this._endBlockNode(Catch, Finally); + } + throw(error) { + return this._leafNode(new Throw(error)); + } + block(body, nodeCount) { + this._blockStarts.push(this._nodes.length); + if (body) this.code(body).endBlock(nodeCount); + return this; + } + endBlock(nodeCount) { + const len = this._blockStarts.pop(); + if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); + const toClose = this._nodes.length - len; + if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); + this._nodes.length = len; + return this; + } + func(name, args = code_1.nil, async, funcBody) { + this._blockNode(new Func(name, args, async)); + if (funcBody) this.code(funcBody).endFunc(); + return this; + } + endFunc() { + return this._endBlockNode(Func); + } + optimize(n = 1) { + while (n-- > 0) { + this._root.optimizeNodes(); + this._root.optimizeNames(this._root.names, this._constants); + } + } + _leafNode(node) { + this._currNode.nodes.push(node); + return this; + } + _blockNode(node) { + this._currNode.nodes.push(node); + this._nodes.push(node); + } + _endBlockNode(N1, N2) { + const n = this._currNode; + if (n instanceof N1 || N2 && n instanceof N2) { + this._nodes.pop(); + return this; + } + throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); + } + _elseNode(node) { + const n = this._currNode; + if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); + this._currNode = n.else = node; + return this; + } + get _root() { + return this._nodes[0]; + } + get _currNode() { + const ns = this._nodes; + return ns[ns.length - 1]; + } + set _currNode(node) { + const ns = this._nodes; + ns[ns.length - 1] = node; + } + }; + exports.CodeGen = CodeGen; + function addNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); + return names; + } + function addExprNames(names, from) { + return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; + } + function optimizeExpr(expr, names, constants) { + if (expr instanceof code_1.Name) return replaceName(expr); + if (!canOptimize(expr)) return expr; + return new code_1._Code(expr._items.reduce((items, c) => { + if (c instanceof code_1.Name) c = replaceName(c); + if (c instanceof code_1._Code) items.push(...c._items); + else items.push(c); + return items; + }, [])); + function replaceName(n) { + const c = constants[n.str]; + if (c === void 0 || names[n.str] !== 1) return n; + delete names[n.str]; + return c; + } + function canOptimize(e) { + return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); + } + } + function subtractNames(names, from) { + for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); + } + function not(x) { + return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; + } + exports.not = not; + const andCode = mappend(exports.operators.AND); + function and(...args) { + return args.reduce(andCode); + } + exports.and = and; + const orCode = mappend(exports.operators.OR); + function or(...args) { + return args.reduce(orCode); + } + exports.or = or; + function mappend(op) { + return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; + } + function par(x) { + return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js +var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; + const codegen_1 = require_codegen(); + const code_1 = require_code$1(); + function toHash(arr) { + const hash = {}; + for (const item of arr) hash[item] = true; + return hash; + } + exports.toHash = toHash; + function alwaysValidSchema(it, schema) { + if (typeof schema == "boolean") return schema; + if (Object.keys(schema).length === 0) return true; + checkUnknownRules(it, schema); + return !schemaHasRules(schema, it.self.RULES.all); + } + exports.alwaysValidSchema = alwaysValidSchema; + function checkUnknownRules(it, schema = it.schema) { + const { opts, self } = it; + if (!opts.strictSchema) return; + if (typeof schema === "boolean") return; + const rules = self.RULES.keywords; + for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); + } + exports.checkUnknownRules = checkUnknownRules; + function schemaHasRules(schema, rules) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (rules[key]) return true; + return false; + } + exports.schemaHasRules = schemaHasRules; + function schemaHasRulesButRef(schema, RULES) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; + return false; + } + exports.schemaHasRulesButRef = schemaHasRulesButRef; + function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { + if (!$data) { + if (typeof schema == "number" || typeof schema == "boolean") return schema; + if (typeof schema == "string") return (0, codegen_1._)`${schema}`; + } + return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; + } + exports.schemaRefOrVal = schemaRefOrVal; + function unescapeFragment(str) { + return unescapeJsonPointer(decodeURIComponent(str)); + } + exports.unescapeFragment = unescapeFragment; + function escapeFragment(str) { + return encodeURIComponent(escapeJsonPointer(str)); + } + exports.escapeFragment = escapeFragment; + function escapeJsonPointer(str) { + if (typeof str == "number") return `${str}`; + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } + exports.escapeJsonPointer = escapeJsonPointer; + function unescapeJsonPointer(str) { + return str.replace(/~1/g, "/").replace(/~0/g, "~"); + } + exports.unescapeJsonPointer = unescapeJsonPointer; + function eachItem(xs, f) { + if (Array.isArray(xs)) for (const x of xs) f(x); + else f(xs); + } + exports.eachItem = eachItem; + function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { + return (gen, from, to, toName) => { + const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); + return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; + }; + } + exports.mergeEvaluated = { + props: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { + gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); + }), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { + if (from === true) gen.assign(to, true); + else { + gen.assign(to, (0, codegen_1._)`${to} || {}`); + setEvaluated(gen, to, from); + } + }), + mergeValues: (from, to) => from === true ? true : { + ...from, + ...to + }, + resultToName: evaluatedPropsToName + }), + items: makeMergeEvaluated({ + mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), + mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), + mergeValues: (from, to) => from === true ? true : Math.max(from, to), + resultToName: (gen, items) => gen.var("items", items) + }) + }; + function evaluatedPropsToName(gen, ps) { + if (ps === true) return gen.var("props", true); + const props = gen.var("props", (0, codegen_1._)`{}`); + if (ps !== void 0) setEvaluated(gen, props, ps); + return props; + } + exports.evaluatedPropsToName = evaluatedPropsToName; + function setEvaluated(gen, props, ps) { + Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); + } + exports.setEvaluated = setEvaluated; + const snippets = {}; + function useFunc(gen, f) { + return gen.scopeValue("func", { + ref: f, + code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) + }); + } + exports.useFunc = useFunc; + var Type; + (function(Type) { + Type[Type["Num"] = 0] = "Num"; + Type[Type["Str"] = 1] = "Str"; + })(Type || (exports.Type = Type = {})); + function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { + if (dataProp instanceof codegen_1.Name) { + const isNumber = dataPropType === Type.Num; + return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; + } + return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); + } + exports.getErrorPath = getErrorPath; + function checkStrictMode(it, msg, mode = it.opts.strictSchema) { + if (!mode) return; + msg = `strict mode: ${msg}`; + if (mode === true) throw new Error(msg); + it.self.logger.warn(msg); + } + exports.checkStrictMode = checkStrictMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js +var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const names = { + data: new codegen_1.Name("data"), + valCxt: new codegen_1.Name("valCxt"), + instancePath: new codegen_1.Name("instancePath"), + parentData: new codegen_1.Name("parentData"), + parentDataProperty: new codegen_1.Name("parentDataProperty"), + rootData: new codegen_1.Name("rootData"), + dynamicAnchors: new codegen_1.Name("dynamicAnchors"), + vErrors: new codegen_1.Name("vErrors"), + errors: new codegen_1.Name("errors"), + this: new codegen_1.Name("this"), + self: new codegen_1.Name("self"), + scope: new codegen_1.Name("scope"), + json: new codegen_1.Name("json"), + jsonPos: new codegen_1.Name("jsonPos"), + jsonLen: new codegen_1.Name("jsonLen"), + jsonPart: new codegen_1.Name("jsonPart") + }; + exports.default = names; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js +var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; + exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; + function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + const errObj = errorObjectCode(cxt, error, errorPaths); + if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); + else returnErrors(it, (0, codegen_1._)`[${errObj}]`); + } + exports.reportError = reportError; + function reportExtraError(cxt, error = exports.keywordError, errorPaths) { + const { it } = cxt; + const { gen, compositeRule, allErrors } = it; + addError(gen, errorObjectCode(cxt, error, errorPaths)); + if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); + } + exports.reportExtraError = reportExtraError; + function resetErrorsCount(gen, errsCount) { + gen.assign(names_1.default.errors, errsCount); + gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); + } + exports.resetErrorsCount = resetErrorsCount; + function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { + /* istanbul ignore if */ + if (errsCount === void 0) throw new Error("ajv implementation error"); + const err = gen.name("err"); + gen.forRange("i", errsCount, names_1.default.errors, (i) => { + gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); + gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); + gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); + if (it.opts.verbose) { + gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); + gen.assign((0, codegen_1._)`${err}.data`, data); + } + }); + } + exports.extendErrors = extendErrors; + function addError(gen, errObj) { + const err = gen.const("err", errObj); + gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); + gen.code((0, codegen_1._)`${names_1.default.errors}++`); + } + function returnErrors(it, errs) { + const { gen, validateName, schemaEnv } = it; + if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, errs); + gen.return(false); + } + } + const E = { + keyword: new codegen_1.Name("keyword"), + schemaPath: new codegen_1.Name("schemaPath"), + params: new codegen_1.Name("params"), + propertyName: new codegen_1.Name("propertyName"), + message: new codegen_1.Name("message"), + schema: new codegen_1.Name("schema"), + parentSchema: new codegen_1.Name("parentSchema") + }; + function errorObjectCode(cxt, error, errorPaths) { + const { createErrors } = cxt.it; + if (createErrors === false) return (0, codegen_1._)`{}`; + return errorObject(cxt, error, errorPaths); + } + function errorObject(cxt, error, errorPaths = {}) { + const { gen, it } = cxt; + const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; + extraErrorProps(cxt, error, keyValues); + return gen.object(...keyValues); + } + function errorInstancePath({ errorPath }, { instancePath }) { + const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; + return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; + } + function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { + let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; + if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; + return [E.schemaPath, schPath]; + } + function extraErrorProps(cxt, { params, message }, keyValues) { + const { keyword, data, schemaValue, it } = cxt; + const { opts, propertyName, topSchemaRef, schemaPath } = it; + keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); + if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); + if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); + if (propertyName) keyValues.push([E.propertyName, propertyName]); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js +var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const boolError = { message: "boolean schema is false" }; + function topBoolOrEmptySchema(it) { + const { gen, schema, validateName } = it; + if (schema === false) falseSchemaError(it, false); + else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, null); + gen.return(true); + } + } + exports.topBoolOrEmptySchema = topBoolOrEmptySchema; + function boolOrEmptySchema(it, valid) { + const { gen, schema } = it; + if (schema === false) { + gen.var(valid, false); + falseSchemaError(it); + } else gen.var(valid, true); + } + exports.boolOrEmptySchema = boolOrEmptySchema; + function falseSchemaError(it, overrideAllErrors) { + const { gen, data } = it; + const cxt = { + gen, + keyword: "false schema", + data, + schema: false, + schemaCode: false, + schemaValue: false, + params: {}, + it + }; + (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js +var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getRules = exports.isJSONType = void 0; + const jsonTypes = new Set([ + "string", + "number", + "integer", + "boolean", + "null", + "object", + "array" + ]); + function isJSONType(x) { + return typeof x == "string" && jsonTypes.has(x); + } + exports.isJSONType = isJSONType; + function getRules() { + const groups = { + number: { + type: "number", + rules: [] + }, + string: { + type: "string", + rules: [] + }, + array: { + type: "array", + rules: [] + }, + object: { + type: "object", + rules: [] + } + }; + return { + types: { + ...groups, + integer: true, + boolean: true, + null: true + }, + rules: [ + { rules: [] }, + groups.number, + groups.string, + groups.array, + groups.object + ], + post: { rules: [] }, + all: {}, + keywords: {} + }; + } + exports.getRules = getRules; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js +var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; + function schemaHasRulesForType({ schema, self }, type) { + const group = self.RULES.types[type]; + return group && group !== true && shouldUseGroup(schema, group); + } + exports.schemaHasRulesForType = schemaHasRulesForType; + function shouldUseGroup(schema, group) { + return group.rules.some((rule) => shouldUseRule(schema, rule)); + } + exports.shouldUseGroup = shouldUseGroup; + function shouldUseRule(schema, rule) { + var _a; + return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); + } + exports.shouldUseRule = shouldUseRule; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js +var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; + const rules_1 = require_rules(); + const applicability_1 = require_applicability(); + const errors_1 = require_errors(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + var DataType; + (function(DataType) { + DataType[DataType["Correct"] = 0] = "Correct"; + DataType[DataType["Wrong"] = 1] = "Wrong"; + })(DataType || (exports.DataType = DataType = {})); + function getSchemaTypes(schema) { + const types = getJSONTypes(schema.type); + if (types.includes("null")) { + if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); + } else { + if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); + if (schema.nullable === true) types.push("null"); + } + return types; + } + exports.getSchemaTypes = getSchemaTypes; + function getJSONTypes(ts) { + const types = Array.isArray(ts) ? ts : ts ? [ts] : []; + if (types.every(rules_1.isJSONType)) return types; + throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); + } + exports.getJSONTypes = getJSONTypes; + function coerceAndCheckDataType(it, types) { + const { gen, data, opts } = it; + const coerceTo = coerceToTypes(types, opts.coerceTypes); + const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); + if (checkTypes) { + const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); + gen.if(wrongType, () => { + if (coerceTo.length) coerceData(it, types, coerceTo); + else reportTypeError(it); + }); + } + return checkTypes; + } + exports.coerceAndCheckDataType = coerceAndCheckDataType; + const COERCIBLE = new Set([ + "string", + "number", + "integer", + "boolean", + "null" + ]); + function coerceToTypes(types, coerceTypes) { + return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; + } + function coerceData(it, types, coerceTo) { + const { gen, data, opts } = it; + const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); + const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); + if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); + gen.if((0, codegen_1._)`${coerced} !== undefined`); + for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); + gen.else(); + reportTypeError(it); + gen.endIf(); + gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { + gen.assign(data, coerced); + assignParentData(it, coerced); + }); + function coerceSpecificType(t) { + switch (t) { + case "string": + gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); + return; + case "number": + gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null + || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "integer": + gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null + || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); + return; + case "boolean": + gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); + return; + case "null": + gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); + gen.assign(coerced, null); + return; + case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" + || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); + } + } + } + function assignParentData({ gen, parentData, parentDataProperty }, expr) { + gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); + } + function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { + const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; + let cond; + switch (dataType) { + case "null": return (0, codegen_1._)`${data} ${EQ} null`; + case "array": + cond = (0, codegen_1._)`Array.isArray(${data})`; + break; + case "object": + cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; + break; + case "integer": + cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); + break; + case "number": + cond = numCond(); + break; + default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; + } + return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); + function numCond(_cond = codegen_1.nil) { + return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); + } + } + exports.checkDataType = checkDataType; + function checkDataTypes(dataTypes, data, strictNums, correct) { + if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); + let cond; + const types = (0, util_1.toHash)(dataTypes); + if (types.array && types.object) { + const notObj = (0, codegen_1._)`typeof ${data} != "object"`; + cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; + delete types.null; + delete types.array; + delete types.object; + } else cond = codegen_1.nil; + if (types.number) delete types.integer; + for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); + return cond; + } + exports.checkDataTypes = checkDataTypes; + const typeError = { + message: ({ schema }) => `must be ${schema}`, + params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` + }; + function reportTypeError(it) { + const cxt = getTypeErrorContext(it); + (0, errors_1.reportError)(cxt, typeError); + } + exports.reportTypeError = reportTypeError; + function getTypeErrorContext(it) { + const { gen, data, schema } = it; + const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); + return { + gen, + keyword: "type", + data, + schema: schema.type, + schemaCode, + schemaValue: schemaCode, + parentSchema: schema, + params: {}, + it + }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js +var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.assignDefaults = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function assignDefaults(it, ty) { + const { properties, items } = it.schema; + if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); + else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); + } + exports.assignDefaults = assignDefaults; + function assignDefault(it, prop, defaultValue) { + const { gen, compositeRule, data, opts } = it; + if (defaultValue === void 0) return; + const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; + if (compositeRule) { + (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); + return; + } + let condition = (0, codegen_1._)`${childData} === undefined`; + if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; + gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js +var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const util_2 = require_util(); + function checkReportMissingProp(cxt, prop) { + const { gen, data, it } = cxt; + gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { + cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); + cxt.error(); + }); + } + exports.checkReportMissingProp = checkReportMissingProp; + function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { + return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); + } + exports.checkMissingProp = checkMissingProp; + function reportMissingProp(cxt, missing) { + cxt.setParams({ missingProperty: missing }, true); + cxt.error(); + } + exports.reportMissingProp = reportMissingProp; + function hasPropFunc(gen) { + return gen.scopeValue("func", { + ref: Object.prototype.hasOwnProperty, + code: (0, codegen_1._)`Object.prototype.hasOwnProperty` + }); + } + exports.hasPropFunc = hasPropFunc; + function isOwnProperty(gen, data, property) { + return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; + } + exports.isOwnProperty = isOwnProperty; + function propertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; + return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; + } + exports.propertyInData = propertyInData; + function noPropertyInData(gen, data, property, ownProperties) { + const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; + return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; + } + exports.noPropertyInData = noPropertyInData; + function allSchemaProperties(schemaMap) { + return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; + } + exports.allSchemaProperties = allSchemaProperties; + function schemaProperties(it, schemaMap) { + return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); + } + exports.schemaProperties = schemaProperties; + function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { + const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; + const valCxt = [ + [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], + [names_1.default.parentData, it.parentData], + [names_1.default.parentDataProperty, it.parentDataProperty], + [names_1.default.rootData, names_1.default.rootData] + ]; + if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); + const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; + return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; + } + exports.callValidateCode = callValidateCode; + const newRegExp = (0, codegen_1._)`new RegExp`; + function usePattern({ gen, it: { opts } }, pattern) { + const u = opts.unicodeRegExp ? "u" : ""; + const { regExp } = opts.code; + const rx = regExp(pattern, u); + return gen.scopeValue("pattern", { + key: rx.toString(), + ref: rx, + code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` + }); + } + exports.usePattern = usePattern; + function validateArray(cxt) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + if (it.allErrors) { + const validArr = gen.let("valid", true); + validateItems(() => gen.assign(validArr, false)); + return validArr; + } + gen.var(valid, true); + validateItems(() => gen.break()); + return valid; + function validateItems(notValid) { + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + gen.if((0, codegen_1.not)(valid), notValid); + }); + } + } + exports.validateArray = validateArray; + function validateUnion(cxt) { + const { gen, schema, keyword, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; + const valid = gen.let("valid", false); + const schValid = gen.name("_valid"); + gen.block(() => schema.forEach((_sch, i) => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: i, + compositeRule: true + }, schValid); + gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); + if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); + })); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + } + exports.validateUnion = validateUnion; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js +var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const code_1 = require_code(); + const errors_1 = require_errors(); + function macroKeywordCode(cxt, def) { + const { gen, keyword, schema, parentSchema, it } = cxt; + const macroSchema = def.macro.call(it.self, schema, parentSchema, it); + const schemaRef = useKeyword(gen, keyword, macroSchema); + if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); + const valid = gen.name("valid"); + cxt.subschema({ + schema: macroSchema, + schemaPath: codegen_1.nil, + errSchemaPath: `${it.errSchemaPath}/${keyword}`, + topSchemaRef: schemaRef, + compositeRule: true + }, valid); + cxt.pass(valid, () => cxt.error(true)); + } + exports.macroKeywordCode = macroKeywordCode; + function funcKeywordCode(cxt, def) { + var _a; + const { gen, keyword, schema, parentSchema, $data, it } = cxt; + checkAsyncKeyword(it, def); + const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); + const valid = gen.let("valid"); + cxt.block$data(valid, validateKeyword); + cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); + function validateKeyword() { + if (def.errors === false) { + assignValid(); + if (def.modifying) modifyData(cxt); + reportErrs(() => cxt.error()); + } else { + const ruleErrs = def.async ? validateAsync() : validateSync(); + if (def.modifying) modifyData(cxt); + reportErrs(() => addErrs(cxt, ruleErrs)); + } + } + function validateAsync() { + const ruleErrs = gen.let("ruleErrs", null); + gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); + return ruleErrs; + } + function validateSync() { + const validateErrs = (0, codegen_1._)`${validateRef}.errors`; + gen.assign(validateErrs, null); + assignValid(codegen_1.nil); + return validateErrs; + } + function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { + const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; + const passSchema = !("compile" in def && !$data || def.schema === false); + gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); + } + function reportErrs(errors) { + var _a$1; + gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); + } + } + exports.funcKeywordCode = funcKeywordCode; + function modifyData(cxt) { + const { gen, data, it } = cxt; + gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); + } + function addErrs(cxt, errs) { + const { gen } = cxt; + gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + (0, errors_1.extendErrors)(cxt); + }, () => cxt.error()); + } + function checkAsyncKeyword({ schemaEnv }, def) { + if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); + } + function useKeyword(gen, keyword, result) { + if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); + return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { + ref: result, + code: (0, codegen_1.stringify)(result) + }); + } + function validSchemaType(schema, schemaType, allowUndefined = false) { + return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); + } + exports.validSchemaType = validSchemaType; + function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { + /* istanbul ignore if */ + if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); + const deps = def.dependencies; + if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); + if (def.validateSchema) { + if (!def.validateSchema(schema[keyword])) { + const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); + if (opts.validateSchema === "log") self.logger.error(msg); + else throw new Error(msg); + } + } + } + exports.validateKeywordUsage = validateKeywordUsage; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js +var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { + if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); + if (keyword !== void 0) { + const sch = it.schema[keyword]; + return schemaProp === void 0 ? { + schema: sch, + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}` + } : { + schema: sch[schemaProp], + schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, + errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` + }; + } + if (schema !== void 0) { + if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); + return { + schema, + schemaPath, + topSchemaRef, + errSchemaPath + }; + } + throw new Error("either \"keyword\" or \"schema\" must be passed"); + } + exports.getSubschema = getSubschema; + function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { + if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); + const { gen } = it; + if (dataProp !== void 0) { + const { errorPath, dataPathArr, opts } = it; + dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); + subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; + subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; + subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; + } + if (data !== void 0) { + dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); + if (propertyName !== void 0) subschema.propertyName = propertyName; + } + if (dataTypes) subschema.dataTypes = dataTypes; + function dataContextProps(_nextData) { + subschema.data = _nextData; + subschema.dataLevel = it.dataLevel + 1; + subschema.dataTypes = []; + it.definedProperties = /* @__PURE__ */ new Set(); + subschema.parentData = it.data; + subschema.dataNames = [...it.dataNames, _nextData]; + } + } + exports.extendSubschemaData = extendSubschemaData; + function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { + if (compositeRule !== void 0) subschema.compositeRule = compositeRule; + if (createErrors !== void 0) subschema.createErrors = createErrors; + if (allErrors !== void 0) subschema.allErrors = allErrors; + subschema.jtdDiscriminator = jtdDiscriminator; + subschema.jtdMetadata = jtdMetadata; + } + exports.extendSubschemaMode = extendSubschemaMode; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js +var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length, i, keys; + if (Array.isArray(a)) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length; i-- !== 0;) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js +var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { + var traverse = module.exports = function(schema, opts, cb) { + if (typeof opts == "function") { + cb = opts; + opts = {}; + } + cb = opts.cb || cb; + var pre = typeof cb == "function" ? cb : cb.pre || function() {}; + var post = cb.post || function() {}; + _traverse(opts, pre, post, schema, "", schema); + }; + traverse.keywords = { + additionalItems: true, + items: true, + contains: true, + additionalProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true + }; + traverse.arrayKeywords = { + items: true, + allOf: true, + anyOf: true, + oneOf: true + }; + traverse.propsKeywords = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependencies: true + }; + traverse.skipKeywords = { + default: true, + enum: true, + const: true, + required: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true + }; + function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { + if (schema && typeof schema == "object" && !Array.isArray(schema)) { + pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + for (var key in schema) { + var sch = schema[key]; + if (Array.isArray(sch)) { + if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); + } else if (key in traverse.propsKeywords) { + if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); + } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); + } + post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); + } + } + function escapeJsonPtr(str) { + return str.replace(/~/g, "~0").replace(/\//g, "~1"); + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js +var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; + const util_1 = require_util(); + const equal = require_fast_deep_equal(); + const traverse = require_json_schema_traverse(); + const SIMPLE_INLINED = new Set([ + "type", + "format", + "pattern", + "maxLength", + "minLength", + "maxProperties", + "minProperties", + "maxItems", + "minItems", + "maximum", + "minimum", + "uniqueItems", + "multipleOf", + "required", + "enum", + "const" + ]); + function inlineRef(schema, limit = true) { + if (typeof schema == "boolean") return true; + if (limit === true) return !hasRef(schema); + if (!limit) return false; + return countKeys(schema) <= limit; + } + exports.inlineRef = inlineRef; + const REF_KEYWORDS = new Set([ + "$ref", + "$recursiveRef", + "$recursiveAnchor", + "$dynamicRef", + "$dynamicAnchor" + ]); + function hasRef(schema) { + for (const key in schema) { + if (REF_KEYWORDS.has(key)) return true; + const sch = schema[key]; + if (Array.isArray(sch) && sch.some(hasRef)) return true; + if (typeof sch == "object" && hasRef(sch)) return true; + } + return false; + } + function countKeys(schema) { + let count = 0; + for (const key in schema) { + if (key === "$ref") return Infinity; + count++; + if (SIMPLE_INLINED.has(key)) continue; + if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); + if (count === Infinity) return Infinity; + } + return count; + } + function getFullPath(resolver, id = "", normalize) { + if (normalize !== false) id = normalizeId(id); + return _getFullPath(resolver, resolver.parse(id)); + } + exports.getFullPath = getFullPath; + function _getFullPath(resolver, p) { + return resolver.serialize(p).split("#")[0] + "#"; + } + exports._getFullPath = _getFullPath; + const TRAILING_SLASH_HASH = /#\/?$/; + function normalizeId(id) { + return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; + } + exports.normalizeId = normalizeId; + function resolveUrl(resolver, baseId, id) { + id = normalizeId(id); + return resolver.resolve(baseId, id); + } + exports.resolveUrl = resolveUrl; + const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; + function getSchemaRefs(schema, baseId) { + if (typeof schema == "boolean") return {}; + const { schemaId, uriResolver } = this.opts; + const schId = normalizeId(schema[schemaId] || baseId); + const baseIds = { "": schId }; + const pathPrefix = getFullPath(uriResolver, schId, false); + const localRefs = {}; + const schemaRefs = /* @__PURE__ */ new Set(); + traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { + if (parentJsonPtr === void 0) return; + const fullPath = pathPrefix + jsonPtr; + let innerBaseId = baseIds[parentJsonPtr]; + if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); + addAnchor.call(this, sch.$anchor); + addAnchor.call(this, sch.$dynamicAnchor); + baseIds[jsonPtr] = innerBaseId; + function addRef(ref) { + const _resolve = this.opts.uriResolver.resolve; + ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); + if (schemaRefs.has(ref)) throw ambiguos(ref); + schemaRefs.add(ref); + let schOrRef = this.refs[ref]; + if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; + if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); + else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { + checkAmbiguosRef(sch, localRefs[ref], ref); + localRefs[ref] = sch; + } else this.refs[ref] = fullPath; + return ref; + } + function addAnchor(anchor) { + if (typeof anchor == "string") { + if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); + addRef.call(this, `#${anchor}`); + } + } + }); + return localRefs; + function checkAmbiguosRef(sch1, sch2, ref) { + if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); + } + function ambiguos(ref) { + return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); + } + } + exports.getSchemaRefs = getSchemaRefs; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js +var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; + const boolSchema_1 = require_boolSchema(); + const dataType_1 = require_dataType(); + const applicability_1 = require_applicability(); + const dataType_2 = require_dataType(); + const defaults_1 = require_defaults(); + const keyword_1 = require_keyword(); + const subschema_1 = require_subschema(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const errors_1 = require_errors(); + function validateFunctionCode(it) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + topSchemaObjCode(it); + return; + } + } + validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); + } + exports.validateFunctionCode = validateFunctionCode; + function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { + if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { + gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); + destructureValCxtES5(gen, opts); + gen.code(body); + }); + else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); + } + function destructureValCxt(opts) { + return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; + } + function destructureValCxtES5(gen, opts) { + gen.if(names_1.default.valCxt, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); + gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); + gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); + }, () => { + gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); + gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); + gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); + gen.var(names_1.default.rootData, names_1.default.data); + if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); + }); + } + function topSchemaObjCode(it) { + const { schema, opts, gen } = it; + validateFunction(it, () => { + if (opts.$comment && schema.$comment) commentKeyword(it); + checkNoDefault(it); + gen.let(names_1.default.vErrors, null); + gen.let(names_1.default.errors, 0); + if (opts.unevaluated) resetEvaluated(it); + typeAndKeywords(it); + returnResults(it); + }); + } + function resetEvaluated(it) { + const { gen, validateName } = it; + it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); + gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); + } + function funcSourceUrl(schema, opts) { + const schId = typeof schema == "object" && schema[opts.schemaId]; + return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; + } + function subschemaCode(it, valid) { + if (isSchemaObj(it)) { + checkKeywords(it); + if (schemaCxtHasRules(it)) { + subSchemaObjCode(it, valid); + return; + } + } + (0, boolSchema_1.boolOrEmptySchema)(it, valid); + } + function schemaCxtHasRules({ schema, self }) { + if (typeof schema == "boolean") return !schema; + for (const key in schema) if (self.RULES.all[key]) return true; + return false; + } + function isSchemaObj(it) { + return typeof it.schema != "boolean"; + } + function subSchemaObjCode(it, valid) { + const { schema, gen, opts } = it; + if (opts.$comment && schema.$comment) commentKeyword(it); + updateContext(it); + checkAsyncSchema(it); + const errsCount = gen.const("_errs", names_1.default.errors); + typeAndKeywords(it, errsCount); + gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + } + function checkKeywords(it) { + (0, util_1.checkUnknownRules)(it); + checkRefsAndKeywords(it); + } + function typeAndKeywords(it, errsCount) { + if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); + const types = (0, dataType_1.getSchemaTypes)(it.schema); + schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); + } + function checkRefsAndKeywords(it) { + const { schema, errSchemaPath, opts, self } = it; + if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); + } + function checkNoDefault(it) { + const { schema, opts } = it; + if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); + } + function updateContext(it) { + const schId = it.schema[it.opts.schemaId]; + if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); + } + function checkAsyncSchema(it) { + if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); + } + function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { + const msg = schema.$comment; + if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); + else if (typeof opts.$comment == "function") { + const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; + const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); + gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); + } + } + function returnResults(it) { + const { gen, schemaEnv, validateName, ValidationError, opts } = it; + if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); + else { + gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); + if (opts.unevaluated) assignEvaluated(it); + gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); + } + } + function assignEvaluated({ gen, evaluated, props, items }) { + if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); + if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); + } + function schemaKeywords(it, types, typeErrors, errsCount) { + const { gen, schema, data, allErrors, opts, self } = it; + const { RULES } = self; + if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { + gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); + return; + } + if (!opts.jtd) checkStrictTypes(it, types); + gen.block(() => { + for (const group of RULES.rules) groupKeywords(group); + groupKeywords(RULES.post); + }); + function groupKeywords(group) { + if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; + if (group.type) { + gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); + iterateKeywords(it, group); + if (types.length === 1 && types[0] === group.type && typeErrors) { + gen.else(); + (0, dataType_2.reportTypeError)(it); + } + gen.endIf(); + } else iterateKeywords(it, group); + if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); + } + } + function iterateKeywords(it, group) { + const { gen, schema, opts: { useDefaults } } = it; + if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); + gen.block(() => { + for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); + }); + } + function checkStrictTypes(it, types) { + if (it.schemaEnv.meta || !it.opts.strictTypes) return; + checkContextTypes(it, types); + if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); + checkKeywordTypes(it, it.dataTypes); + } + function checkContextTypes(it, types) { + if (!types.length) return; + if (!it.dataTypes.length) { + it.dataTypes = types; + return; + } + types.forEach((t) => { + if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); + }); + narrowSchemaTypes(it, types); + } + function checkMultipleTypes(it, ts) { + if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); + } + function checkKeywordTypes(it, ts) { + const rules = it.self.RULES.all; + for (const keyword in rules) { + const rule = rules[keyword]; + if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { + const { type } = rule.definition; + if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); + } + } + } + function hasApplicableType(schTs, kwdT) { + return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); + } + function includesType(ts, t) { + return ts.includes(t) || t === "integer" && ts.includes("number"); + } + function narrowSchemaTypes(it, withTypes) { + const ts = []; + for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); + else if (withTypes.includes("integer") && t === "number") ts.push("integer"); + it.dataTypes = ts; + } + function strictTypesError(it, msg) { + const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; + msg += ` at "${schemaPath}" (strictTypes)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); + } + var KeywordCxt = class { + constructor(it, def, keyword) { + (0, keyword_1.validateKeywordUsage)(it, def, keyword); + this.gen = it.gen; + this.allErrors = it.allErrors; + this.keyword = keyword; + this.data = it.data; + this.schema = it.schema[keyword]; + this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; + this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); + this.schemaType = def.schemaType; + this.parentSchema = it.schema; + this.params = {}; + this.it = it; + this.def = def; + if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); + else { + this.schemaCode = this.schemaValue; + if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); + } + if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); + } + result(condition, successAction, failAction) { + this.failResult((0, codegen_1.not)(condition), successAction, failAction); + } + failResult(condition, successAction, failAction) { + this.gen.if(condition); + if (failAction) failAction(); + else this.error(); + if (successAction) { + this.gen.else(); + successAction(); + if (this.allErrors) this.gen.endIf(); + } else if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + pass(condition, failAction) { + this.failResult((0, codegen_1.not)(condition), void 0, failAction); + } + fail(condition) { + if (condition === void 0) { + this.error(); + if (!this.allErrors) this.gen.if(false); + return; + } + this.gen.if(condition); + this.error(); + if (this.allErrors) this.gen.endIf(); + else this.gen.else(); + } + fail$data(condition) { + if (!this.$data) return this.fail(condition); + const { schemaCode } = this; + this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); + } + error(append, errorParams, errorPaths) { + if (errorParams) { + this.setParams(errorParams); + this._error(append, errorPaths); + this.setParams({}); + return; + } + this._error(append, errorPaths); + } + _error(append, errorPaths) { + (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); + } + $dataError() { + (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); + } + reset() { + if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); + (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); + } + ok(cond) { + if (!this.allErrors) this.gen.if(cond); + } + setParams(obj, assign) { + if (assign) Object.assign(this.params, obj); + else this.params = obj; + } + block$data(valid, codeBlock, $dataValid = codegen_1.nil) { + this.gen.block(() => { + this.check$data(valid, $dataValid); + codeBlock(); + }); + } + check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { + if (!this.$data) return; + const { gen, schemaCode, schemaType, def } = this; + gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); + if (valid !== codegen_1.nil) gen.assign(valid, true); + if (schemaType.length || def.validateSchema) { + gen.elseIf(this.invalid$data()); + this.$dataError(); + if (valid !== codegen_1.nil) gen.assign(valid, false); + } + gen.else(); + } + invalid$data() { + const { gen, schemaCode, schemaType, def, it } = this; + return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); + function wrong$DataType() { + if (schemaType.length) { + /* istanbul ignore if */ + if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); + const st = Array.isArray(schemaType) ? schemaType : [schemaType]; + return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; + } + return codegen_1.nil; + } + function invalid$DataSchema() { + if (def.validateSchema) { + const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); + return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; + } + return codegen_1.nil; + } + } + subschema(appl, valid) { + const subschema = (0, subschema_1.getSubschema)(this.it, appl); + (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); + (0, subschema_1.extendSubschemaMode)(subschema, appl); + const nextContext = { + ...this.it, + ...subschema, + items: void 0, + props: void 0 + }; + subschemaCode(nextContext, valid); + return nextContext; + } + mergeEvaluated(schemaCxt, toName) { + const { it, gen } = this; + if (!it.opts.unevaluated) return; + if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); + if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); + } + mergeValidEvaluated(schemaCxt, valid) { + const { it, gen } = this; + if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { + gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); + return true; + } + } + }; + exports.KeywordCxt = KeywordCxt; + function keywordCode(it, keyword, def, ruleType) { + const cxt = new KeywordCxt(it, def, keyword); + if ("code" in def) def.code(cxt, ruleType); + else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); + else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); + } + const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; + const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; + function getData($data, { dataLevel, dataNames, dataPathArr }) { + let jsonPointer; + let data; + if ($data === "") return names_1.default.rootData; + if ($data[0] === "/") { + if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); + jsonPointer = $data; + data = names_1.default.rootData; + } else { + const matches = RELATIVE_JSON_POINTER.exec($data); + if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); + const up = +matches[1]; + jsonPointer = matches[2]; + if (jsonPointer === "#") { + if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); + return dataPathArr[dataLevel - up]; + } + if (up > dataLevel) throw new Error(errorMsg("data", up)); + data = dataNames[dataLevel - up]; + if (!jsonPointer) return data; + } + let expr = data; + const segments = jsonPointer.split("/"); + for (const segment of segments) if (segment) { + data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; + expr = (0, codegen_1._)`${expr} && ${data}`; + } + return expr; + function errorMsg(pointerType, up) { + return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; + } + } + exports.getData = getData; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js +var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + var ValidationError = class extends Error { + constructor(errors) { + super("validation failed"); + this.errors = errors; + this.ajv = this.validation = true; + } + }; + exports.default = ValidationError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js +var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const resolve_1 = require_resolve(); + var MissingRefError = class extends Error { + constructor(resolver, baseId, ref, msg) { + super(msg || `can't resolve reference ${ref} from id ${baseId}`); + this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); + this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); + } + }; + exports.default = MissingRefError; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js +var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; + const codegen_1 = require_codegen(); + const validation_error_1 = require_validation_error(); + const names_1 = require_names(); + const resolve_1 = require_resolve(); + const util_1 = require_util(); + const validate_1 = require_validate(); + var SchemaEnv = class { + constructor(env) { + var _a; + this.refs = {}; + this.dynamicAnchors = {}; + let schema; + if (typeof env.schema == "object") schema = env.schema; + this.schema = env.schema; + this.schemaId = env.schemaId; + this.root = env.root || this; + this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); + this.schemaPath = env.schemaPath; + this.localRefs = env.localRefs; + this.meta = env.meta; + this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; + this.refs = {}; + } + }; + exports.SchemaEnv = SchemaEnv; + function compileSchema(sch) { + const _sch = getCompilingSchema.call(this, sch); + if (_sch) return _sch; + const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); + const { es5, lines } = this.opts.code; + const { ownProperties } = this.opts; + const gen = new codegen_1.CodeGen(this.scope, { + es5, + lines, + ownProperties + }); + let _ValidationError; + if (sch.$async) _ValidationError = gen.scopeValue("Error", { + ref: validation_error_1.default, + code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` + }); + const validateName = gen.scopeName("validate"); + sch.validateName = validateName; + const schemaCxt = { + gen, + allErrors: this.opts.allErrors, + data: names_1.default.data, + parentData: names_1.default.parentData, + parentDataProperty: names_1.default.parentDataProperty, + dataNames: [names_1.default.data], + dataPathArr: [codegen_1.nil], + dataLevel: 0, + dataTypes: [], + definedProperties: /* @__PURE__ */ new Set(), + topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { + ref: sch.schema, + code: (0, codegen_1.stringify)(sch.schema) + } : { ref: sch.schema }), + validateName, + ValidationError: _ValidationError, + schema: sch.schema, + schemaEnv: sch, + rootId, + baseId: sch.baseId || rootId, + schemaPath: codegen_1.nil, + errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), + errorPath: (0, codegen_1._)`""`, + opts: this.opts, + self: this + }; + let sourceCode; + try { + this._compilations.add(sch); + (0, validate_1.validateFunctionCode)(schemaCxt); + gen.optimize(this.opts.code.optimize); + const validateCode = gen.toString(); + sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; + if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); + const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); + this.scope.value(validateName, { ref: validate }); + validate.errors = null; + validate.schema = sch.schema; + validate.schemaEnv = sch; + if (sch.$async) validate.$async = true; + if (this.opts.code.source === true) validate.source = { + validateName, + validateCode, + scopeValues: gen._values + }; + if (this.opts.unevaluated) { + const { props, items } = schemaCxt; + validate.evaluated = { + props: props instanceof codegen_1.Name ? void 0 : props, + items: items instanceof codegen_1.Name ? void 0 : items, + dynamicProps: props instanceof codegen_1.Name, + dynamicItems: items instanceof codegen_1.Name + }; + if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); + } + sch.validate = validate; + return sch; + } catch (e) { + delete sch.validate; + delete sch.validateName; + if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); + throw e; + } finally { + this._compilations.delete(sch); + } + } + exports.compileSchema = compileSchema; + function resolveRef(root, baseId, ref) { + var _a; + ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); + const schOrFunc = root.refs[ref]; + if (schOrFunc) return schOrFunc; + let _sch = resolve.call(this, root, ref); + if (_sch === void 0) { + const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; + const { schemaId } = this.opts; + if (schema) _sch = new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + if (_sch === void 0) return; + return root.refs[ref] = inlineOrCompile.call(this, _sch); + } + exports.resolveRef = resolveRef; + function inlineOrCompile(sch) { + if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; + return sch.validate ? sch : compileSchema.call(this, sch); + } + function getCompilingSchema(schEnv) { + for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; + } + exports.getCompilingSchema = getCompilingSchema; + function sameSchemaEnv(s1, s2) { + return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; + } + function resolve(root, ref) { + let sch; + while (typeof (sch = this.refs[ref]) == "string") ref = sch; + return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); + } + function resolveSchema(root, ref) { + const p = this.opts.uriResolver.parse(ref); + const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); + let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); + if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); + const id = (0, resolve_1.normalizeId)(refPath); + const schOrRef = this.refs[id] || this.schemas[id]; + if (typeof schOrRef == "string") { + const sch = resolveSchema.call(this, root, schOrRef); + if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; + return getJsonPointer.call(this, p, sch); + } + if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; + if (!schOrRef.validate) compileSchema.call(this, schOrRef); + if (id === (0, resolve_1.normalizeId)(ref)) { + const { schema } = schOrRef; + const { schemaId } = this.opts; + const schId = schema[schemaId]; + if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + return new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + } + return getJsonPointer.call(this, p, schOrRef); + } + exports.resolveSchema = resolveSchema; + const PREVENT_SCOPE_CHANGE = new Set([ + "properties", + "patternProperties", + "enum", + "dependencies", + "definitions" + ]); + function getJsonPointer(parsedRef, { baseId, schema, root }) { + var _a; + if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; + for (const part of parsedRef.fragment.slice(1).split("/")) { + if (typeof schema === "boolean") return; + const partSchema = schema[(0, util_1.unescapeFragment)(part)]; + if (partSchema === void 0) return; + schema = partSchema; + const schId = typeof schema === "object" && schema[this.opts.schemaId]; + if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); + } + let env; + if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { + const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); + env = resolveSchema.call(this, root, $ref); + } + const { schemaId } = this.opts; + env = env || new SchemaEnv({ + schema, + schemaId, + root, + baseId + }); + if (env.schema !== env.root.schema) return env; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json +var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", + "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", + "type": "object", + "required": ["$data"], + "properties": { "$data": { + "type": "string", + "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] + } }, + "additionalProperties": false + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js +var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { + /** @type {(value: string) => boolean} */ + const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); + /** @type {(value: string) => boolean} */ + const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); + /** + * @param {Array} input + * @returns {string} + */ + function stringArrayToHexStripped(input) { + let acc = ""; + let code = 0; + let i = 0; + for (i = 0; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (code === 48) continue; + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + break; + } + for (i += 1; i < input.length; i++) { + code = input[i].charCodeAt(0); + if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; + acc += input[i]; + } + return acc; + } + /** + * @typedef {Object} GetIPV6Result + * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. + * @property {string} address - The parsed IPv6 address. + * @property {string} [zone] - The zone identifier, if present. + */ + /** + * @param {string} value + * @returns {boolean} + */ + const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); + /** + * @param {Array} buffer + * @returns {boolean} + */ + function consumeIsZone(buffer) { + buffer.length = 0; + return true; + } + /** + * @param {Array} buffer + * @param {Array} address + * @param {GetIPV6Result} output + * @returns {boolean} + */ + function consumeHextets(buffer, address, output) { + if (buffer.length) { + const hex = stringArrayToHexStripped(buffer); + if (hex !== "") address.push(hex); + else { + output.error = true; + return false; + } + buffer.length = 0; + } + return true; + } + /** + * @param {string} input + * @returns {GetIPV6Result} + */ + function getIPV6(input) { + let tokenCount = 0; + const output = { + error: false, + address: "", + zone: "" + }; + /** @type {Array} */ + const address = []; + /** @type {Array} */ + const buffer = []; + let endipv6Encountered = false; + let endIpv6 = false; + let consume = consumeHextets; + for (let i = 0; i < input.length; i++) { + const cursor = input[i]; + if (cursor === "[" || cursor === "]") continue; + if (cursor === ":") { + if (endipv6Encountered === true) endIpv6 = true; + if (!consume(buffer, address, output)) break; + if (++tokenCount > 7) { + output.error = true; + break; + } + if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; + address.push(":"); + continue; + } else if (cursor === "%") { + if (!consume(buffer, address, output)) break; + consume = consumeIsZone; + } else { + buffer.push(cursor); + continue; + } + } + if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); + else if (endIpv6) address.push(buffer.join("")); + else address.push(stringArrayToHexStripped(buffer)); + output.address = address.join(""); + return output; + } + /** + * @typedef {Object} NormalizeIPv6Result + * @property {string} host - The normalized host. + * @property {string} [escapedHost] - The escaped host. + * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. + */ + /** + * @param {string} host + * @returns {NormalizeIPv6Result} + */ + function normalizeIPv6(host) { + if (findToken(host, ":") < 2) return { + host, + isIPV6: false + }; + const ipv6 = getIPV6(host); + if (!ipv6.error) { + let newHost = ipv6.address; + let escapedHost = ipv6.address; + if (ipv6.zone) { + newHost += "%" + ipv6.zone; + escapedHost += "%25" + ipv6.zone; + } + return { + host: newHost, + isIPV6: true, + escapedHost + }; + } else return { + host, + isIPV6: false + }; + } + /** + * @param {string} str + * @param {string} token + * @returns {number} + */ + function findToken(str, token) { + let ind = 0; + for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; + return ind; + } + /** + * @param {string} path + * @returns {string} + * + * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 + */ + function removeDotSegments(path) { + let input = path; + const output = []; + let nextSlash = -1; + let len = 0; + while (len = input.length) { + if (len === 1) if (input === ".") break; + else if (input === "/") { + output.push("/"); + break; + } else { + output.push(input); + break; + } + else if (len === 2) { + if (input[0] === ".") { + if (input[1] === ".") break; + else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === "." || input[1] === "/") { + output.push("/"); + break; + } + } + } else if (len === 3) { + if (input === "/..") { + if (output.length !== 0) output.pop(); + output.push("/"); + break; + } + } + if (input[0] === ".") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(3); + continue; + } + } else if (input[1] === "/") { + input = input.slice(2); + continue; + } + } else if (input[0] === "/") { + if (input[1] === ".") { + if (input[2] === "/") { + input = input.slice(2); + continue; + } else if (input[2] === ".") { + if (input[3] === "/") { + input = input.slice(3); + if (output.length !== 0) output.pop(); + continue; + } + } + } + } + if ((nextSlash = input.indexOf("/", 1)) === -1) { + output.push(input); + break; + } else { + output.push(input.slice(0, nextSlash)); + input = input.slice(nextSlash); + } + } + return output.join(""); + } + /** + * @param {import('../types/index').URIComponent} component + * @param {boolean} esc + * @returns {import('../types/index').URIComponent} + */ + function normalizeComponentEncoding(component, esc) { + const func = esc !== true ? escape : unescape; + if (component.scheme !== void 0) component.scheme = func(component.scheme); + if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); + if (component.host !== void 0) component.host = func(component.host); + if (component.path !== void 0) component.path = func(component.path); + if (component.query !== void 0) component.query = func(component.query); + if (component.fragment !== void 0) component.fragment = func(component.fragment); + return component; + } + /** + * @param {import('../types/index').URIComponent} component + * @returns {string|undefined} + */ + function recomposeAuthority(component) { + const uriTokens = []; + if (component.userinfo !== void 0) { + uriTokens.push(component.userinfo); + uriTokens.push("@"); + } + if (component.host !== void 0) { + let host = unescape(component.host); + if (!isIPv4(host)) { + const ipV6res = normalizeIPv6(host); + if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; + else host = component.host; + } + uriTokens.push(host); + } + if (typeof component.port === "number" || typeof component.port === "string") { + uriTokens.push(":"); + uriTokens.push(String(component.port)); + } + return uriTokens.length ? uriTokens.join("") : void 0; + } + module.exports = { + nonSimpleDomain, + recomposeAuthority, + normalizeComponentEncoding, + removeDotSegments, + isIPv4, + isUUID, + normalizeIPv6, + stringArrayToHexStripped + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js +var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { isUUID } = require_utils(); + const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; + const supportedSchemeNames = [ + "http", + "https", + "ws", + "wss", + "urn", + "urn:uuid" + ]; + /** @typedef {supportedSchemeNames[number]} SchemeName */ + /** + * @param {string} name + * @returns {name is SchemeName} + */ + function isValidSchemeName(name) { + return supportedSchemeNames.indexOf(name) !== -1; + } + /** + * @callback SchemeFn + * @param {import('../types/index').URIComponent} component + * @param {import('../types/index').Options} options + * @returns {import('../types/index').URIComponent} + */ + /** + * @typedef {Object} SchemeHandler + * @property {SchemeName} scheme - The scheme name. + * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. + * @property {SchemeFn} parse - Function to parse the URI component for this scheme. + * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. + * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. + * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. + * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. + */ + /** + * @param {import('../types/index').URIComponent} wsComponent + * @returns {boolean} + */ + function wsIsSecure(wsComponent) { + if (wsComponent.secure === true) return true; + else if (wsComponent.secure === false) return false; + else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); + else return false; + } + /** @type {SchemeFn} */ + function httpParse(component) { + if (!component.host) component.error = component.error || "HTTP URIs must have a host."; + return component; + } + /** @type {SchemeFn} */ + function httpSerialize(component) { + const secure = String(component.scheme).toLowerCase() === "https"; + if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; + if (!component.path) component.path = "/"; + return component; + } + /** @type {SchemeFn} */ + function wsParse(wsComponent) { + wsComponent.secure = wsIsSecure(wsComponent); + wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); + wsComponent.path = void 0; + wsComponent.query = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function wsSerialize(wsComponent) { + if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; + if (typeof wsComponent.secure === "boolean") { + wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; + wsComponent.secure = void 0; + } + if (wsComponent.resourceName) { + const [path, query] = wsComponent.resourceName.split("?"); + wsComponent.path = path && path !== "/" ? path : void 0; + wsComponent.query = query; + wsComponent.resourceName = void 0; + } + wsComponent.fragment = void 0; + return wsComponent; + } + /** @type {SchemeFn} */ + function urnParse(urnComponent, options) { + if (!urnComponent.path) { + urnComponent.error = "URN can not be parsed"; + return urnComponent; + } + const matches = urnComponent.path.match(URN_REG); + if (matches) { + const scheme = options.scheme || urnComponent.scheme || "urn"; + urnComponent.nid = matches[1].toLowerCase(); + urnComponent.nss = matches[2]; + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); + urnComponent.path = void 0; + if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); + } else urnComponent.error = urnComponent.error || "URN can not be parsed."; + return urnComponent; + } + /** @type {SchemeFn} */ + function urnSerialize(urnComponent, options) { + if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); + const scheme = options.scheme || urnComponent.scheme || "urn"; + const nid = urnComponent.nid.toLowerCase(); + const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); + if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); + const uriComponent = urnComponent; + const nss = urnComponent.nss; + uriComponent.path = `${nid || options.nid}:${nss}`; + options.skipEscape = true; + return uriComponent; + } + /** @type {SchemeFn} */ + function urnuuidParse(urnComponent, options) { + const uuidComponent = urnComponent; + uuidComponent.uuid = uuidComponent.nss; + uuidComponent.nss = void 0; + if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; + return uuidComponent; + } + /** @type {SchemeFn} */ + function urnuuidSerialize(uuidComponent) { + const urnComponent = uuidComponent; + urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); + return urnComponent; + } + const http = { + scheme: "http", + domainHost: true, + parse: httpParse, + serialize: httpSerialize + }; + const https = { + scheme: "https", + domainHost: http.domainHost, + parse: httpParse, + serialize: httpSerialize + }; + const ws = { + scheme: "ws", + domainHost: true, + parse: wsParse, + serialize: wsSerialize + }; + const wss = { + scheme: "wss", + domainHost: ws.domainHost, + parse: ws.parse, + serialize: ws.serialize + }; + const urn = { + scheme: "urn", + parse: urnParse, + serialize: urnSerialize, + skipNormalize: true + }; + const urnuuid = { + scheme: "urn:uuid", + parse: urnuuidParse, + serialize: urnuuidSerialize, + skipNormalize: true + }; + const SCHEMES = { + http, + https, + ws, + wss, + urn, + "urn:uuid": urnuuid + }; + Object.setPrototypeOf(SCHEMES, null); + /** + * @param {string|undefined} scheme + * @returns {SchemeHandler|undefined} + */ + function getSchemeHandler(scheme) { + return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; + } + module.exports = { + wsIsSecure, + SCHEMES, + isValidSchemeName, + getSchemeHandler + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js +var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { + const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); + const { SCHEMES, getSchemeHandler } = require_schemes(); + /** + * @template {import('./types/index').URIComponent|string} T + * @param {T} uri + * @param {import('./types/index').Options} [options] + * @returns {T} + */ + function normalize(uri, options) { + if (typeof uri === "string") uri = serialize(parse(uri, options), options); + else if (typeof uri === "object") uri = parse(serialize(uri, options), options); + return uri; + } + /** + * @param {string} baseURI + * @param {string} relativeURI + * @param {import('./types/index').Options} [options] + * @returns {string} + */ + function resolve(baseURI, relativeURI, options) { + const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; + const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); + schemelessOptions.skipEscape = true; + return serialize(resolved, schemelessOptions); + } + /** + * @param {import ('./types/index').URIComponent} base + * @param {import ('./types/index').URIComponent} relative + * @param {import('./types/index').Options} [options] + * @param {boolean} [skipNormalization=false] + * @returns {import ('./types/index').URIComponent} + */ + function resolveComponent(base, relative, options, skipNormalization) { + /** @type {import('./types/index').URIComponent} */ + const target = {}; + if (!skipNormalization) { + base = parse(serialize(base, options), options); + relative = parse(serialize(relative, options), options); + } + options = options || {}; + if (!options.tolerant && relative.scheme) { + target.scheme = relative.scheme; + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { + target.userinfo = relative.userinfo; + target.host = relative.host; + target.port = relative.port; + target.path = removeDotSegments(relative.path || ""); + target.query = relative.query; + } else { + if (!relative.path) { + target.path = base.path; + if (relative.query !== void 0) target.query = relative.query; + else target.query = base.query; + } else { + if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); + else { + if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; + else if (!base.path) target.path = relative.path; + else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; + target.path = removeDotSegments(target.path); + } + target.query = relative.query; + } + target.userinfo = base.userinfo; + target.host = base.host; + target.port = base.port; + } + target.scheme = base.scheme; + } + target.fragment = relative.fragment; + return target; + } + /** + * @param {import ('./types/index').URIComponent|string} uriA + * @param {import ('./types/index').URIComponent|string} uriB + * @param {import ('./types/index').Options} options + * @returns {boolean} + */ + function equal(uriA, uriB, options) { + if (typeof uriA === "string") { + uriA = unescape(uriA); + uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { + ...options, + skipEscape: true + }); + if (typeof uriB === "string") { + uriB = unescape(uriB); + uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { + ...options, + skipEscape: true + }); + } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { + ...options, + skipEscape: true + }); + return uriA.toLowerCase() === uriB.toLowerCase(); + } + /** + * @param {Readonly} cmpts + * @param {import('./types/index').Options} [opts] + * @returns {string} + */ + function serialize(cmpts, opts) { + const component = { + host: cmpts.host, + scheme: cmpts.scheme, + userinfo: cmpts.userinfo, + port: cmpts.port, + path: cmpts.path, + query: cmpts.query, + nid: cmpts.nid, + nss: cmpts.nss, + uuid: cmpts.uuid, + fragment: cmpts.fragment, + reference: cmpts.reference, + resourceName: cmpts.resourceName, + secure: cmpts.secure, + error: "" + }; + const options = Object.assign({}, opts); + const uriTokens = []; + const schemeHandler = getSchemeHandler(options.scheme || component.scheme); + if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); + if (component.path !== void 0) if (!options.skipEscape) { + component.path = escape(component.path); + if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); + } else component.path = unescape(component.path); + if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); + const authority = recomposeAuthority(component); + if (authority !== void 0) { + if (options.reference !== "suffix") uriTokens.push("//"); + uriTokens.push(authority); + if (component.path && component.path[0] !== "/") uriTokens.push("/"); + } + if (component.path !== void 0) { + let s = component.path; + if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); + if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); + uriTokens.push(s); + } + if (component.query !== void 0) uriTokens.push("?", component.query); + if (component.fragment !== void 0) uriTokens.push("#", component.fragment); + return uriTokens.join(""); + } + const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; + /** + * @param {string} uri + * @param {import('./types/index').Options} [opts] + * @returns + */ + function parse(uri, opts) { + const options = Object.assign({}, opts); + /** @type {import('./types/index').URIComponent} */ + const parsed = { + scheme: void 0, + userinfo: void 0, + host: "", + port: void 0, + path: "", + query: void 0, + fragment: void 0 + }; + let isIP = false; + if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; + else uri = "//" + uri; + const matches = uri.match(URI_PARSE); + if (matches) { + parsed.scheme = matches[1]; + parsed.userinfo = matches[3]; + parsed.host = matches[4]; + parsed.port = parseInt(matches[5], 10); + parsed.path = matches[6] || ""; + parsed.query = matches[7]; + parsed.fragment = matches[8]; + if (isNaN(parsed.port)) parsed.port = matches[5]; + if (parsed.host) if (isIPv4(parsed.host) === false) { + const ipv6result = normalizeIPv6(parsed.host); + parsed.host = ipv6result.host.toLowerCase(); + isIP = ipv6result.isIPV6; + } else isIP = true; + if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; + else if (parsed.scheme === void 0) parsed.reference = "relative"; + else if (parsed.fragment === void 0) parsed.reference = "absolute"; + else parsed.reference = "uri"; + if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; + const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); + if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { + if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { + parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); + } catch (e) { + parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; + } + } + if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { + if (uri.indexOf("%") !== -1) { + if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); + if (parsed.host !== void 0) parsed.host = unescape(parsed.host); + } + if (parsed.path) parsed.path = escape(unescape(parsed.path)); + if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); + } + if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); + } else parsed.error = parsed.error || "URI can not be parsed."; + return parsed; + } + const fastUri = { + SCHEMES, + normalize, + resolve, + resolveComponent, + equal, + serialize, + parse + }; + module.exports = fastUri; + module.exports.default = fastUri; + module.exports.fastUri = fastUri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js +var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const uri = require_fast_uri(); + uri.code = "require(\"ajv/dist/runtime/uri\").default"; + exports.default = uri; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js +var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + const validation_error_1 = require_validation_error(); + const ref_error_1 = require_ref_error(); + const rules_1 = require_rules(); + const compile_1 = require_compile(); + const codegen_2 = require_codegen(); + const resolve_1 = require_resolve(); + const dataType_1 = require_dataType(); + const util_1 = require_util(); + const $dataRefSchema = require_data(); + const uri_1 = require_uri(); + const defaultRegExp = (str, flags) => new RegExp(str, flags); + defaultRegExp.code = "new RegExp"; + const META_IGNORE_OPTIONS = [ + "removeAdditional", + "useDefaults", + "coerceTypes" + ]; + const EXT_SCOPE_NAMES = new Set([ + "validate", + "serialize", + "parse", + "wrapper", + "root", + "schema", + "keyword", + "pattern", + "formats", + "validate$data", + "func", + "obj", + "Error" + ]); + const removedOptions = { + errorDataPath: "", + format: "`validateFormats: false` can be used instead.", + nullable: "\"nullable\" keyword is supported by default.", + jsonPointers: "Deprecated jsPropertySyntax can be used instead.", + extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", + missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", + processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", + sourceCode: "Use option `code: {source: true}`", + strictDefaults: "It is default now, see option `strict`.", + strictKeywords: "It is default now, see option `strict`.", + uniqueItems: "\"uniqueItems\" keyword is always validated.", + unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", + cache: "Map is used as cache, schema object as key.", + serialize: "Map is used as cache, schema object as key.", + ajvErrors: "It is default now." + }; + const deprecatedOptions = { + ignoreKeywordsWithRef: "", + jsPropertySyntax: "", + unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." + }; + const MAX_EXPRESSION = 200; + function requiredOptions(o) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; + const s = o.strict; + const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; + const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; + const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; + const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; + return { + strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, + strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, + strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", + strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", + strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, + code: o.code ? { + ...o.code, + optimize, + regExp + } : { + optimize, + regExp + }, + loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, + loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, + meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, + messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, + inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, + schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", + addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, + validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, + validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, + unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, + int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, + uriResolver + }; + } + var Ajv = class { + constructor(opts = {}) { + this.schemas = {}; + this.refs = {}; + this.formats = {}; + this._compilations = /* @__PURE__ */ new Set(); + this._loading = {}; + this._cache = /* @__PURE__ */ new Map(); + opts = this.opts = { + ...opts, + ...requiredOptions(opts) + }; + const { es5, lines } = this.opts.code; + this.scope = new codegen_2.ValueScope({ + scope: {}, + prefixes: EXT_SCOPE_NAMES, + es5, + lines + }); + this.logger = getLogger(opts.logger); + const formatOpt = opts.validateFormats; + opts.validateFormats = false; + this.RULES = (0, rules_1.getRules)(); + checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); + checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); + this._metaOpts = getMetaSchemaOptions.call(this); + if (opts.formats) addInitialFormats.call(this); + this._addVocabularies(); + this._addDefaultMetaSchema(); + if (opts.keywords) addInitialKeywords.call(this, opts.keywords); + if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); + addInitialSchemas.call(this); + opts.validateFormats = formatOpt; + } + _addVocabularies() { + this.addKeyword("$async"); + } + _addDefaultMetaSchema() { + const { $data, meta, schemaId } = this.opts; + let _dataRefSchema = $dataRefSchema; + if (schemaId === "id") { + _dataRefSchema = { ...$dataRefSchema }; + _dataRefSchema.id = _dataRefSchema.$id; + delete _dataRefSchema.$id; + } + if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); + } + defaultMeta() { + const { meta, schemaId } = this.opts; + return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; + } + validate(schemaKeyRef, data) { + let v; + if (typeof schemaKeyRef == "string") { + v = this.getSchema(schemaKeyRef); + if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); + } else v = this.compile(schemaKeyRef); + const valid = v(data); + if (!("$async" in v)) this.errors = v.errors; + return valid; + } + compile(schema, _meta) { + const sch = this._addSchema(schema, _meta); + return sch.validate || this._compileSchemaEnv(sch); + } + compileAsync(schema, meta) { + if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); + const { loadSchema } = this.opts; + return runCompileAsync.call(this, schema, meta); + async function runCompileAsync(_schema, _meta) { + await loadMetaSchema.call(this, _schema.$schema); + const sch = this._addSchema(_schema, _meta); + return sch.validate || _compileAsync.call(this, sch); + } + async function loadMetaSchema($ref) { + if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); + } + async function _compileAsync(sch) { + try { + return this._compileSchemaEnv(sch); + } catch (e) { + if (!(e instanceof ref_error_1.default)) throw e; + checkLoaded.call(this, e); + await loadMissingSchema.call(this, e.missingSchema); + return _compileAsync.call(this, sch); + } + } + function checkLoaded({ missingSchema: ref, missingRef }) { + if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); + } + async function loadMissingSchema(ref) { + const _schema = await _loadSchema.call(this, ref); + if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); + if (!this.refs[ref]) this.addSchema(_schema, ref, meta); + } + async function _loadSchema(ref) { + const p = this._loading[ref]; + if (p) return p; + try { + return await (this._loading[ref] = loadSchema(ref)); + } finally { + delete this._loading[ref]; + } + } + } + addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { + if (Array.isArray(schema)) { + for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); + return this; + } + let id; + if (typeof schema === "object") { + const { schemaId } = this.opts; + id = schema[schemaId]; + if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); + } + key = (0, resolve_1.normalizeId)(key || id); + this._checkUnique(key); + this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); + return this; + } + addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { + this.addSchema(schema, key, true, _validateSchema); + return this; + } + validateSchema(schema, throwOrLogError) { + if (typeof schema == "boolean") return true; + let $schema; + $schema = schema.$schema; + if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); + $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); + if (!$schema) { + this.logger.warn("meta-schema not available"); + this.errors = null; + return true; + } + const valid = this.validate($schema, schema); + if (!valid && throwOrLogError) { + const message = "schema is invalid: " + this.errorsText(); + if (this.opts.validateSchema === "log") this.logger.error(message); + else throw new Error(message); + } + return valid; + } + getSchema(keyRef) { + let sch; + while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; + if (sch === void 0) { + const { schemaId } = this.opts; + const root = new compile_1.SchemaEnv({ + schema: {}, + schemaId + }); + sch = compile_1.resolveSchema.call(this, root, keyRef); + if (!sch) return; + this.refs[keyRef] = sch; + } + return sch.validate || this._compileSchemaEnv(sch); + } + removeSchema(schemaKeyRef) { + if (schemaKeyRef instanceof RegExp) { + this._removeAllSchemas(this.schemas, schemaKeyRef); + this._removeAllSchemas(this.refs, schemaKeyRef); + return this; + } + switch (typeof schemaKeyRef) { + case "undefined": + this._removeAllSchemas(this.schemas); + this._removeAllSchemas(this.refs); + this._cache.clear(); + return this; + case "string": { + const sch = getSchEnv.call(this, schemaKeyRef); + if (typeof sch == "object") this._cache.delete(sch.schema); + delete this.schemas[schemaKeyRef]; + delete this.refs[schemaKeyRef]; + return this; + } + case "object": { + const cacheKey = schemaKeyRef; + this._cache.delete(cacheKey); + let id = schemaKeyRef[this.opts.schemaId]; + if (id) { + id = (0, resolve_1.normalizeId)(id); + delete this.schemas[id]; + delete this.refs[id]; + } + return this; + } + default: throw new Error("ajv.removeSchema: invalid parameter"); + } + } + addVocabulary(definitions) { + for (const def of definitions) this.addKeyword(def); + return this; + } + addKeyword(kwdOrDef, def) { + let keyword; + if (typeof kwdOrDef == "string") { + keyword = kwdOrDef; + if (typeof def == "object") { + this.logger.warn("these parameters are deprecated, see docs for addKeyword"); + def.keyword = keyword; + } + } else if (typeof kwdOrDef == "object" && def === void 0) { + def = kwdOrDef; + keyword = def.keyword; + if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); + } else throw new Error("invalid addKeywords parameters"); + checkKeyword.call(this, keyword, def); + if (!def) { + (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); + return this; + } + keywordMetaschema.call(this, def); + const definition = { + ...def, + type: (0, dataType_1.getJSONTypes)(def.type), + schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) + }; + (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); + return this; + } + getKeyword(keyword) { + const rule = this.RULES.all[keyword]; + return typeof rule == "object" ? rule.definition : !!rule; + } + removeKeyword(keyword) { + const { RULES } = this; + delete RULES.keywords[keyword]; + delete RULES.all[keyword]; + for (const group of RULES.rules) { + const i = group.rules.findIndex((rule) => rule.keyword === keyword); + if (i >= 0) group.rules.splice(i, 1); + } + return this; + } + addFormat(name, format) { + if (typeof format == "string") format = new RegExp(format); + this.formats[name] = format; + return this; + } + errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { + if (!errors || errors.length === 0) return "No errors"; + return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); + } + $dataMetaSchema(metaSchema, keywordsJsonPointers) { + const rules = this.RULES.all; + metaSchema = JSON.parse(JSON.stringify(metaSchema)); + for (const jsonPointer of keywordsJsonPointers) { + const segments = jsonPointer.split("/").slice(1); + let keywords = metaSchema; + for (const seg of segments) keywords = keywords[seg]; + for (const key in rules) { + const rule = rules[key]; + if (typeof rule != "object") continue; + const { $data } = rule.definition; + const schema = keywords[key]; + if ($data && schema) keywords[key] = schemaOrData(schema); + } + } + return metaSchema; + } + _removeAllSchemas(schemas, regex) { + for (const keyRef in schemas) { + const sch = schemas[keyRef]; + if (!regex || regex.test(keyRef)) { + if (typeof sch == "string") delete schemas[keyRef]; + else if (sch && !sch.meta) { + this._cache.delete(sch.schema); + delete schemas[keyRef]; + } + } + } + } + _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { + let id; + const { schemaId } = this.opts; + if (typeof schema == "object") id = schema[schemaId]; + else if (this.opts.jtd) throw new Error("schema must be object"); + else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); + let sch = this._cache.get(schema); + if (sch !== void 0) return sch; + baseId = (0, resolve_1.normalizeId)(id || baseId); + const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); + sch = new compile_1.SchemaEnv({ + schema, + schemaId, + meta, + baseId, + localRefs + }); + this._cache.set(sch.schema, sch); + if (addSchema && !baseId.startsWith("#")) { + if (baseId) this._checkUnique(baseId); + this.refs[baseId] = sch; + } + if (validateSchema) this.validateSchema(schema, true); + return sch; + } + _checkUnique(id) { + if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); + } + _compileSchemaEnv(sch) { + if (sch.meta) this._compileMetaSchema(sch); + else compile_1.compileSchema.call(this, sch); + /* istanbul ignore if */ + if (!sch.validate) throw new Error("ajv implementation error"); + return sch.validate; + } + _compileMetaSchema(sch) { + const currentOpts = this.opts; + this.opts = this._metaOpts; + try { + compile_1.compileSchema.call(this, sch); + } finally { + this.opts = currentOpts; + } + } + }; + Ajv.ValidationError = validation_error_1.default; + Ajv.MissingRefError = ref_error_1.default; + exports.default = Ajv; + function checkOptions(checkOpts, options, msg, log = "error") { + for (const key in checkOpts) { + const opt = key; + if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); + } + } + function getSchEnv(keyRef) { + keyRef = (0, resolve_1.normalizeId)(keyRef); + return this.schemas[keyRef] || this.refs[keyRef]; + } + function addInitialSchemas() { + const optsSchemas = this.opts.schemas; + if (!optsSchemas) return; + if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); + else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); + } + function addInitialFormats() { + for (const name in this.opts.formats) { + const format = this.opts.formats[name]; + if (format) this.addFormat(name, format); + } + } + function addInitialKeywords(defs) { + if (Array.isArray(defs)) { + this.addVocabulary(defs); + return; + } + this.logger.warn("keywords option as map is deprecated, pass array"); + for (const keyword in defs) { + const def = defs[keyword]; + if (!def.keyword) def.keyword = keyword; + this.addKeyword(def); + } + } + function getMetaSchemaOptions() { + const metaOpts = { ...this.opts }; + for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; + return metaOpts; + } + const noLogs = { + log() {}, + warn() {}, + error() {} + }; + function getLogger(logger) { + if (logger === false) return noLogs; + if (logger === void 0) return console; + if (logger.log && logger.warn && logger.error) return logger; + throw new Error("logger must implement log, warn and error methods"); + } + const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; + function checkKeyword(keyword, def) { + const { RULES } = this; + (0, util_1.eachItem)(keyword, (kwd) => { + if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); + if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); + }); + if (!def) return; + if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); + } + function addRule(keyword, definition, dataType) { + var _a; + const post = definition === null || definition === void 0 ? void 0 : definition.post; + if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); + const { RULES } = this; + let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); + if (!ruleGroup) { + ruleGroup = { + type: dataType, + rules: [] + }; + RULES.rules.push(ruleGroup); + } + RULES.keywords[keyword] = true; + if (!definition) return; + const rule = { + keyword, + definition: { + ...definition, + type: (0, dataType_1.getJSONTypes)(definition.type), + schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) + } + }; + if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); + else ruleGroup.rules.push(rule); + RULES.all[keyword] = rule; + (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); + } + function addBeforeRule(ruleGroup, rule, before) { + const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); + if (i >= 0) ruleGroup.rules.splice(i, 0, rule); + else { + ruleGroup.rules.push(rule); + this.logger.warn(`rule ${before} is not defined`); + } + } + function keywordMetaschema(def) { + let { metaSchema } = def; + if (metaSchema === void 0) return; + if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); + def.validateSchema = this.compile(metaSchema, true); + } + const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; + function schemaOrData(schema) { + return { anyOf: [schema, $dataRef] }; + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js +var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "id", + code() { + throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js +var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.callRef = exports.getValidate = void 0; + const ref_error_1 = require_ref_error(); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const util_1 = require_util(); + const def = { + keyword: "$ref", + schemaType: "string", + code(cxt) { + const { gen, schema: $ref, it } = cxt; + const { baseId, schemaEnv: env, validateName, opts, self } = it; + const { root } = env; + if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); + const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); + if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); + if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); + return inlineRefSchema(schOrEnv); + function callRootRef() { + if (env === root) return callRef(cxt, validateName, env, env.$async); + const rootName = gen.scopeValue("root", { ref: root }); + return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); + } + function callValidate(sch) { + callRef(cxt, getValidate(cxt, sch), sch, sch.$async); + } + function inlineRefSchema(sch) { + const schName = gen.scopeValue("schema", opts.code.source === true ? { + ref: sch, + code: (0, codegen_1.stringify)(sch) + } : { ref: sch }); + const valid = gen.name("valid"); + const schCxt = cxt.subschema({ + schema: sch, + dataTypes: [], + schemaPath: codegen_1.nil, + topSchemaRef: schName, + errSchemaPath: $ref + }, valid); + cxt.mergeEvaluated(schCxt); + cxt.ok(valid); + } + } + }; + function getValidate(cxt, sch) { + const { gen } = cxt; + return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; + } + exports.getValidate = getValidate; + function callRef(cxt, v, sch, $async) { + const { gen, it } = cxt; + const { allErrors, schemaEnv: env, opts } = it; + const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; + if ($async) callAsyncRef(); + else callSyncRef(); + function callAsyncRef() { + if (!env.$async) throw new Error("async schema referenced by sync schema"); + const valid = gen.let("valid"); + gen.try(() => { + gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); + addEvaluatedFrom(v); + if (!allErrors) gen.assign(valid, true); + }, (e) => { + gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); + addErrorsFrom(e); + if (!allErrors) gen.assign(valid, false); + }); + cxt.ok(valid); + } + function callSyncRef() { + cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); + } + function addErrorsFrom(source) { + const errs = (0, codegen_1._)`${source}.errors`; + gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); + gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); + } + function addEvaluatedFrom(source) { + var _a; + if (!it.opts.unevaluated) return; + const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; + if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { + if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); + } else { + const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); + it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); + } + if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { + if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); + } else { + const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); + it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); + } + } + } + exports.callRef = callRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js +var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const id_1 = require_id(); + const ref_1 = require_ref(); + const core = [ + "$schema", + "$id", + "$defs", + "$vocabulary", + { keyword: "$comment" }, + "definitions", + id_1.default, + ref_1.default + ]; + exports.default = core; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js +var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + maximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + minimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + exclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + exclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const def = { + keyword: Object.keys(KWDs), + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js +var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "multipleOf", + type: "number", + schemaType: "number", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, + params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, schemaCode, it } = cxt; + const prec = it.opts.multipleOfPrecision; + const res = gen.let("res"); + const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; + cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js +var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + function ucs2length(str) { + const len = str.length; + let length = 0; + let pos = 0; + let value; + while (pos < len) { + length++; + value = str.charCodeAt(pos++); + if (value >= 55296 && value <= 56319 && pos < len) { + value = str.charCodeAt(pos); + if ((value & 64512) === 56320) pos++; + } + } + return length; + } + exports.default = ucs2length; + ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js +var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const ucs2length_1 = require_ucs2length(); + const def = { + keyword: ["maxLength", "minLength"], + type: "string", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxLength" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode, it } = cxt; + const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; + const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; + cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js +var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const util_1 = require_util(); + const codegen_1 = require_codegen(); + const def = { + keyword: "pattern", + type: "string", + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const u = it.opts.unicodeRegExp ? "u" : ""; + if ($data) { + const { regExp } = it.opts.code; + const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); + const valid = gen.let("valid"); + gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); + cxt.fail$data((0, codegen_1._)`!${valid}`); + } else { + const regExp = (0, code_1.usePattern)(cxt, schema); + cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js +var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxProperties", "minProperties"], + type: "object", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxProperties" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js +var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "required", + type: "object", + schemaType: "array", + $data: true, + error: { + message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, + params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` + }, + code(cxt) { + const { gen, schema, schemaCode, data, $data, it } = cxt; + const { opts } = it; + if (!$data && schema.length === 0) return; + const useLoop = schema.length >= opts.loopRequired; + if (it.allErrors) allErrorsMode(); + else exitOnErrorMode(); + if (opts.strictRequired) { + const props = cxt.parentSchema.properties; + const { definedProperties } = cxt.it; + for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { + const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; + (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); + } + } + function allErrorsMode() { + if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); + else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); + } + function exitOnErrorMode() { + const missing = gen.let("missing"); + if (useLoop || $data) { + const valid = gen.let("valid", true); + cxt.block$data(valid, () => loopUntilMissing(missing, valid)); + cxt.ok(valid); + } else { + gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + function loopAllRequired() { + gen.forOf("prop", schemaCode, (prop) => { + cxt.setParams({ missingProperty: prop }); + gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); + }); + } + function loopUntilMissing(missing, valid) { + cxt.setParams({ missingProperty: missing }); + gen.forOf(missing, schemaCode, () => { + gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(); + gen.break(); + }); + }, codegen_1.nil); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js +var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: ["maxItems", "minItems"], + type: "array", + schemaType: "number", + $data: true, + error: { + message({ keyword, schemaCode }) { + const comp = keyword === "maxItems" ? "more" : "fewer"; + return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; + }, + params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` + }, + code(cxt) { + const { keyword, data, schemaCode } = cxt; + const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; + cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js +var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const equal = require_fast_deep_equal(); + equal.code = "require(\"ajv/dist/runtime/equal\").default"; + exports.default = equal; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js +var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dataType_1 = require_dataType(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "uniqueItems", + type: "array", + schemaType: "boolean", + $data: true, + error: { + message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, + params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` + }, + code(cxt) { + const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; + if (!$data && !schema) return; + const valid = gen.let("valid"); + const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; + cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); + cxt.ok(valid); + function validateUniqueItems() { + const i = gen.let("i", (0, codegen_1._)`${data}.length`); + const j = gen.let("j"); + cxt.setParams({ + i, + j + }); + gen.assign(valid, true); + gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); + } + function canOptimize() { + return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); + } + function loopN(i, j) { + const item = gen.name("item"); + const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); + const indices = gen.const("indices", (0, codegen_1._)`{}`); + gen.for((0, codegen_1._)`;${i}--;`, () => { + gen.let(item, (0, codegen_1._)`${data}[${i}]`); + gen.if(wrongType, (0, codegen_1._)`continue`); + if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); + gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { + gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); + cxt.error(); + gen.assign(valid, false).break(); + }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); + }); + } + function loopN2(i, j) { + const eql = (0, util_1.useFunc)(gen, equal_1.default); + const outer = gen.name("outer"); + gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { + cxt.error(); + gen.assign(valid, false).break(outer); + }))); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js +var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "const", + $data: true, + error: { + message: "must be equal to constant", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schemaCode, schema } = cxt; + if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); + else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js +var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const equal_1 = require_equal(); + const def = { + keyword: "enum", + schemaType: "array", + $data: true, + error: { + message: "must be equal to one of the allowed values", + params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` + }, + code(cxt) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); + const useLoop = schema.length >= it.opts.loopEnum; + let eql; + const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); + let valid; + if (useLoop || $data) { + valid = gen.let("valid"); + cxt.block$data(valid, loopEnum); + } else { + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const vSchema = gen.const("vSchema", schemaCode); + valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); + } + cxt.pass(valid); + function loopEnum() { + gen.assign(valid, false); + gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); + } + function equalCode(vSchema, i) { + const sch = schema[i]; + return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js +var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const limitNumber_1 = require_limitNumber(); + const multipleOf_1 = require_multipleOf(); + const limitLength_1 = require_limitLength(); + const pattern_1 = require_pattern(); + const limitProperties_1 = require_limitProperties(); + const required_1 = require_required(); + const limitItems_1 = require_limitItems(); + const uniqueItems_1 = require_uniqueItems(); + const const_1 = require_const(); + const enum_1 = require_enum(); + const validation = [ + limitNumber_1.default, + multipleOf_1.default, + limitLength_1.default, + pattern_1.default, + limitProperties_1.default, + required_1.default, + limitItems_1.default, + uniqueItems_1.default, + { + keyword: "type", + schemaType: ["string", "array"] + }, + { + keyword: "nullable", + schemaType: "boolean" + }, + const_1.default, + enum_1.default + ]; + exports.default = validation; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js +var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateAdditionalItems = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "additionalItems", + type: "array", + schemaType: ["boolean", "object"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { parentSchema, it } = cxt; + const { items } = parentSchema; + if (!Array.isArray(items)) { + (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); + return; + } + validateAdditionalItems(cxt, items); + } + }; + function validateAdditionalItems(cxt, items) { + const { gen, schema, data, keyword, it } = cxt; + it.items = true; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items.length }); + cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); + cxt.ok(valid); + } + function validateItems(valid) { + gen.forRange("i", items.length, len, (i) => { + cxt.subschema({ + keyword, + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + exports.validateAdditionalItems = validateAdditionalItems; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js +var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateTuple = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const def = { + keyword: "items", + type: "array", + schemaType: [ + "object", + "array", + "boolean" + ], + before: "uniqueItems", + code(cxt) { + const { schema, it } = cxt; + if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + function validateTuple(cxt, extraItems, schArr = cxt.schema) { + const { gen, parentSchema, data, keyword, it } = cxt; + checkStrictTuple(parentSchema); + if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); + const valid = gen.name("valid"); + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + schArr.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ + keyword, + schemaProp: i, + dataProp: i + }, valid)); + cxt.ok(valid); + }); + function checkStrictTuple(sch) { + const { opts, errSchemaPath } = it; + const l = schArr.length; + const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); + if (opts.strictTuples && !fullTuple) { + const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; + (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); + } + } + } + exports.validateTuple = validateTuple; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js +var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const items_1 = require_items(); + const def = { + keyword: "prefixItems", + type: "array", + schemaType: ["array"], + before: "uniqueItems", + code: (cxt) => (0, items_1.validateTuple)(cxt, "items") + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js +var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + const additionalItems_1 = require_additionalItems(); + const def = { + keyword: "items", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { schema, parentSchema, it } = cxt; + const { prefixItems } = parentSchema; + it.items = true; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); + else cxt.ok((0, code_1.validateArray)(cxt)); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js +var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "contains", + type: "array", + schemaType: ["object", "boolean"], + before: "uniqueItems", + trackErrors: true, + error: { + message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, + params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + let min; + let max; + const { minContains, maxContains } = parentSchema; + if (it.opts.next) { + min = minContains === void 0 ? 1 : minContains; + max = maxContains; + } else min = 1; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + cxt.setParams({ + min, + max + }); + if (max === void 0 && min === 0) { + (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); + return; + } + if (max !== void 0 && min > max) { + (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); + cxt.fail(); + return; + } + if ((0, util_1.alwaysValidSchema)(it, schema)) { + let cond = (0, codegen_1._)`${len} >= ${min}`; + if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; + cxt.pass(cond); + return; + } + it.items = true; + const valid = gen.name("valid"); + if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); + else if (min === 0) { + gen.let(valid, true); + if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); + } else { + gen.let(valid, false); + validateItemsWithCount(); + } + cxt.result(valid, () => cxt.reset()); + function validateItemsWithCount() { + const schValid = gen.name("_valid"); + const count = gen.let("count", 0); + validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); + } + function validateItems(_valid, block) { + gen.forRange("i", 0, len, (i) => { + cxt.subschema({ + keyword: "contains", + dataProp: i, + dataPropType: util_1.Type.Num, + compositeRule: true + }, _valid); + block(); + }); + } + function checkLimits(count) { + gen.code((0, codegen_1._)`${count}++`); + if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); + else { + gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); + if (min === 1) gen.assign(valid, true); + else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js +var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const code_1 = require_code(); + exports.error = { + message: ({ params: { property, depsCount, deps } }) => { + const property_ies = depsCount === 1 ? "property" : "properties"; + return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; + }, + params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, + missingProperty: ${missingProperty}, + depsCount: ${depsCount}, + deps: ${deps}}` + }; + const def = { + keyword: "dependencies", + type: "object", + schemaType: "object", + error: exports.error, + code(cxt) { + const [propDeps, schDeps] = splitDependencies(cxt); + validatePropertyDeps(cxt, propDeps); + validateSchemaDeps(cxt, schDeps); + } + }; + function splitDependencies({ schema }) { + const propertyDeps = {}; + const schemaDeps = {}; + for (const key in schema) { + if (key === "__proto__") continue; + const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; + deps[key] = schema[key]; + } + return [propertyDeps, schemaDeps]; + } + function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { + const { gen, data, it } = cxt; + if (Object.keys(propertyDeps).length === 0) return; + const missing = gen.let("missing"); + for (const prop in propertyDeps) { + const deps = propertyDeps[prop]; + if (deps.length === 0) continue; + const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); + cxt.setParams({ + property: prop, + depsCount: deps.length, + deps: deps.join(", ") + }); + if (it.allErrors) gen.if(hasProperty, () => { + for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); + }); + else { + gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); + (0, code_1.reportMissingProp)(cxt, missing); + gen.else(); + } + } + } + exports.validatePropertyDeps = validatePropertyDeps; + function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { + const { gen, data, keyword, it } = cxt; + const valid = gen.name("valid"); + for (const prop in schemaDeps) { + if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { + const schCxt = cxt.subschema({ + keyword, + schemaProp: prop + }, valid); + cxt.mergeValidEvaluated(schCxt, valid); + }, () => gen.var(valid, true)); + cxt.ok(valid); + } + } + exports.validateSchemaDeps = validateSchemaDeps; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js +var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "propertyNames", + type: "object", + schemaType: ["object", "boolean"], + error: { + message: "property name must be valid", + params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) return; + const valid = gen.name("valid"); + gen.forIn("key", data, (key) => { + cxt.setParams({ propertyName: key }); + cxt.subschema({ + keyword: "propertyNames", + data: key, + dataTypes: ["string"], + propertyName: key, + compositeRule: true + }, valid); + gen.if((0, codegen_1.not)(valid), () => { + cxt.error(true); + if (!it.allErrors) gen.break(); + }); + }); + cxt.ok(valid); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js +var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const util_1 = require_util(); + const def = { + keyword: "additionalProperties", + type: ["object"], + schemaType: ["boolean", "object"], + allowUndefined: true, + trackErrors: true, + error: { + message: "must NOT have additional properties", + params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` + }, + code(cxt) { + const { gen, schema, parentSchema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, opts } = it; + it.props = true; + if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; + const props = (0, code_1.allSchemaProperties)(parentSchema.properties); + const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); + checkAdditionalProperties(); + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function checkAdditionalProperties() { + gen.forIn("key", data, (key) => { + if (!props.length && !patProps.length) additionalPropertyCode(key); + else gen.if(isAdditional(key), () => additionalPropertyCode(key)); + }); + } + function isAdditional(key) { + let definedProp; + if (props.length > 8) { + const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); + definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); + } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); + else definedProp = codegen_1.nil; + if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); + return (0, codegen_1.not)(definedProp); + } + function deleteAdditional(key) { + gen.code((0, codegen_1._)`delete ${data}[${key}]`); + } + function additionalPropertyCode(key) { + if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { + deleteAdditional(key); + return; + } + if (schema === false) { + cxt.setParams({ additionalProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + if (opts.removeAdditional === "failing") { + applyAdditionalSchema(key, valid, false); + gen.if((0, codegen_1.not)(valid), () => { + cxt.reset(); + deleteAdditional(key); + }); + } else { + applyAdditionalSchema(key, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + } + function applyAdditionalSchema(key, valid, errors) { + const subschema = { + keyword: "additionalProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }; + if (errors === false) Object.assign(subschema, { + compositeRule: true, + createErrors: false, + allErrors: false + }); + cxt.subschema(subschema, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js +var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const validate_1 = require_validate(); + const code_1 = require_code(); + const util_1 = require_util(); + const additionalProperties_1 = require_additionalProperties(); + const def = { + keyword: "properties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, parentSchema, data, it } = cxt; + if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); + const allProps = (0, code_1.allSchemaProperties)(schema); + for (const prop of allProps) it.definedProperties.add(prop); + if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); + const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); + if (properties.length === 0) return; + const valid = gen.name("valid"); + for (const prop of properties) { + if (hasDefault(prop)) applyPropertySchema(prop); + else { + gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); + applyPropertySchema(prop); + if (!it.allErrors) gen.else().var(valid, true); + gen.endIf(); + } + cxt.it.definedProperties.add(prop); + cxt.ok(valid); + } + function hasDefault(prop) { + return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; + } + function applyPropertySchema(prop) { + cxt.subschema({ + keyword: "properties", + schemaProp: prop, + dataProp: prop + }, valid); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js +var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const code_1 = require_code(); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const util_2 = require_util(); + const def = { + keyword: "patternProperties", + type: "object", + schemaType: "object", + code(cxt) { + const { gen, schema, data, parentSchema, it } = cxt; + const { opts } = it; + const patterns = (0, code_1.allSchemaProperties)(schema); + const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); + if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; + const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; + const valid = gen.name("valid"); + if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); + const { props } = it; + validatePatternProperties(); + function validatePatternProperties() { + for (const pat of patterns) { + if (checkProperties) checkMatchingProperties(pat); + if (it.allErrors) validateProperties(pat); + else { + gen.var(valid, true); + validateProperties(pat); + gen.if(valid); + } + } + } + function checkMatchingProperties(pat) { + for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); + } + function validateProperties(pat) { + gen.forIn("key", data, (key) => { + gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { + const alwaysValid = alwaysValidPatterns.includes(pat); + if (!alwaysValid) cxt.subschema({ + keyword: "patternProperties", + schemaProp: pat, + dataProp: key, + dataPropType: util_2.Type.Str + }, valid); + if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); + else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js +var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "not", + schemaType: ["object", "boolean"], + trackErrors: true, + code(cxt) { + const { gen, schema, it } = cxt; + if ((0, util_1.alwaysValidSchema)(it, schema)) { + cxt.fail(); + return; + } + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "not", + compositeRule: true, + createErrors: false, + allErrors: false + }, valid); + cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); + }, + error: { message: "must NOT be valid" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js +var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const def = { + keyword: "anyOf", + schemaType: "array", + trackErrors: true, + code: require_code().validateUnion, + error: { message: "must match a schema in anyOf" } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js +var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "oneOf", + schemaType: "array", + trackErrors: true, + error: { + message: "must match exactly one schema in oneOf", + params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` + }, + code(cxt) { + const { gen, schema, parentSchema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + if (it.opts.discriminator && parentSchema.discriminator) return; + const schArr = schema; + const valid = gen.let("valid", false); + const passing = gen.let("passing", null); + const schValid = gen.name("_valid"); + cxt.setParams({ passing }); + gen.block(validateOneOf); + cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); + function validateOneOf() { + schArr.forEach((sch, i) => { + let schCxt; + if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); + else schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp: i, + compositeRule: true + }, schValid); + if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); + gen.if(schValid, () => { + gen.assign(valid, true); + gen.assign(passing, i); + if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); + }); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js +var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: "allOf", + schemaType: "array", + code(cxt) { + const { gen, schema, it } = cxt; + /* istanbul ignore if */ + if (!Array.isArray(schema)) throw new Error("ajv implementation error"); + const valid = gen.name("valid"); + schema.forEach((sch, i) => { + if ((0, util_1.alwaysValidSchema)(it, sch)) return; + const schCxt = cxt.subschema({ + keyword: "allOf", + schemaProp: i + }, valid); + cxt.ok(valid); + cxt.mergeEvaluated(schCxt); + }); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js +var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "if", + schemaType: ["object", "boolean"], + trackErrors: true, + error: { + message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, + params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` + }, + code(cxt) { + const { gen, parentSchema, it } = cxt; + if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); + const hasThen = hasSchema(it, "then"); + const hasElse = hasSchema(it, "else"); + if (!hasThen && !hasElse) return; + const valid = gen.let("valid", true); + const schValid = gen.name("_valid"); + validateIf(); + cxt.reset(); + if (hasThen && hasElse) { + const ifClause = gen.let("ifClause"); + cxt.setParams({ ifClause }); + gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); + } else if (hasThen) gen.if(schValid, validateClause("then")); + else gen.if((0, codegen_1.not)(schValid), validateClause("else")); + cxt.pass(valid, () => cxt.error(true)); + function validateIf() { + const schCxt = cxt.subschema({ + keyword: "if", + compositeRule: true, + createErrors: false, + allErrors: false + }, schValid); + cxt.mergeEvaluated(schCxt); + } + function validateClause(keyword, ifClause) { + return () => { + const schCxt = cxt.subschema({ keyword }, schValid); + gen.assign(valid, schValid); + cxt.mergeValidEvaluated(schCxt, valid); + if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); + else cxt.setParams({ ifClause: keyword }); + }; + } + } + }; + function hasSchema(it, keyword) { + const schema = it.schema[keyword]; + return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js +var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["then", "else"], + schemaType: ["object", "boolean"], + code({ keyword, parentSchema, it }) { + if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js +var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const additionalItems_1 = require_additionalItems(); + const prefixItems_1 = require_prefixItems(); + const items_1 = require_items(); + const items2020_1 = require_items2020(); + const contains_1 = require_contains(); + const dependencies_1 = require_dependencies(); + const propertyNames_1 = require_propertyNames(); + const additionalProperties_1 = require_additionalProperties(); + const properties_1 = require_properties(); + const patternProperties_1 = require_patternProperties(); + const not_1 = require_not(); + const anyOf_1 = require_anyOf(); + const oneOf_1 = require_oneOf(); + const allOf_1 = require_allOf(); + const if_1 = require_if(); + const thenElse_1 = require_thenElse(); + function getApplicator(draft2020 = false) { + const applicator = [ + not_1.default, + anyOf_1.default, + oneOf_1.default, + allOf_1.default, + if_1.default, + thenElse_1.default, + propertyNames_1.default, + additionalProperties_1.default, + dependencies_1.default, + properties_1.default, + patternProperties_1.default + ]; + if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); + else applicator.push(additionalItems_1.default, items_1.default); + applicator.push(contains_1.default); + return applicator; + } + exports.default = getApplicator; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js +var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const def = { + keyword: "format", + type: ["number", "string"], + schemaType: "string", + $data: true, + error: { + message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, + params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` + }, + code(cxt, ruleType) { + const { gen, data, $data, schema, schemaCode, it } = cxt; + const { opts, errSchemaPath, schemaEnv, self } = it; + if (!opts.validateFormats) return; + if ($data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); + const fType = gen.let("fType"); + const format = gen.let("format"); + gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); + cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); + function unknownFmt() { + if (opts.strictSchema === false) return codegen_1.nil; + return (0, codegen_1._)`${schemaCode} && !${format}`; + } + function invalidFmt() { + const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; + const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; + return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; + } + } + function validateFormat() { + const formatDef = self.formats[schema]; + if (!formatDef) { + unknownFormat(); + return; + } + if (formatDef === true) return; + const [fmtType, format, fmtRef] = getFormat(formatDef); + if (fmtType === ruleType) cxt.pass(validCondition()); + function unknownFormat() { + if (opts.strictSchema === false) { + self.logger.warn(unknownMsg()); + return; + } + throw new Error(unknownMsg()); + function unknownMsg() { + return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; + } + } + function getFormat(fmtDef) { + const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; + const fmt = gen.scopeValue("formats", { + key: schema, + ref: fmtDef, + code + }); + if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ + fmtDef.type || "string", + fmtDef.validate, + (0, codegen_1._)`${fmt}.validate` + ]; + return [ + "string", + fmtDef, + fmt + ]; + } + function validCondition() { + if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { + if (!schemaEnv.$async) throw new Error("async format in sync schema"); + return (0, codegen_1._)`await ${fmtRef}(${data})`; + } + return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js +var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const format = [require_format$2().default]; + exports.default = format; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js +var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.contentVocabulary = exports.metadataVocabulary = void 0; + exports.metadataVocabulary = [ + "title", + "description", + "default", + "deprecated", + "readOnly", + "writeOnly", + "examples" + ]; + exports.contentVocabulary = [ + "contentMediaType", + "contentEncoding", + "contentSchema" + ]; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js +var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft7Vocabularies = [ + core_1.default, + validation_1.default, + (0, applicator_1.default)(), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary + ]; + exports.default = draft7Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js +var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.DiscrError = void 0; + var DiscrError; + (function(DiscrError) { + DiscrError["Tag"] = "tag"; + DiscrError["Mapping"] = "mapping"; + })(DiscrError || (exports.DiscrError = DiscrError = {})); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js +var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const types_1 = require_types(); + const compile_1 = require_compile(); + const ref_error_1 = require_ref_error(); + const util_1 = require_util(); + const def = { + keyword: "discriminator", + type: "object", + schemaType: "object", + error: { + message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, + params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` + }, + code(cxt) { + const { gen, data, schema, parentSchema, it } = cxt; + const { oneOf } = parentSchema; + if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); + const tagName = schema.propertyName; + if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); + if (schema.mapping) throw new Error("discriminator: mapping is not supported"); + if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); + const valid = gen.let("valid", false); + const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); + gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { + discrError: types_1.DiscrError.Tag, + tag, + tagName + })); + cxt.ok(valid); + function validateMapping() { + const mapping = getMapping(); + gen.if(false); + for (const tagValue in mapping) { + gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); + gen.assign(valid, applyTagSchema(mapping[tagValue])); + } + gen.else(); + cxt.error(false, { + discrError: types_1.DiscrError.Mapping, + tag, + tagName + }); + gen.endIf(); + } + function applyTagSchema(schemaProp) { + const _valid = gen.name("valid"); + const schCxt = cxt.subschema({ + keyword: "oneOf", + schemaProp + }, _valid); + cxt.mergeEvaluated(schCxt, codegen_1.Name); + return _valid; + } + function getMapping() { + var _a; + const oneOfMapping = {}; + const topRequired = hasRequired(parentSchema); + let tagRequired = true; + for (let i = 0; i < oneOf.length; i++) { + let sch = oneOf[i]; + if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { + const ref = sch.$ref; + sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); + if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; + if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); + } + const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; + if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); + tagRequired = tagRequired && (topRequired || hasRequired(sch)); + addMappings(propSch, i); + } + if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); + return oneOfMapping; + function hasRequired({ required }) { + return Array.isArray(required) && required.includes(tagName); + } + function addMappings(sch, i) { + if (sch.const) addMapping(sch.const, i); + else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); + else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); + } + function addMapping(tagValue, i) { + if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); + oneOfMapping[tagValue] = i; + } + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json +var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "http://json-schema.org/draft-07/schema#", + "title": "Core schema meta-schema", + "definitions": { + "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$ref": "#" } + }, + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + }, + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$comment": { "type": "string" }, + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "readOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, + "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "additionalItems": { "$ref": "#" }, + "items": { + "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], + "default": true + }, + "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, + "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "contains": { "$ref": "#" }, + "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, + "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/definitions/stringArray" }, + "additionalProperties": { "$ref": "#" }, + "definitions": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "properties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$ref": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependencies": { + "type": "object", + "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } + }, + "propertyNames": { "$ref": "#" }, + "const": true, + "enum": { + "type": "array", + "items": true, + "minItems": 1, + "uniqueItems": true + }, + "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/definitions/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "format": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "if": { "$ref": "#" }, + "then": { "$ref": "#" }, + "else": { "$ref": "#" }, + "allOf": { "$ref": "#/definitions/schemaArray" }, + "anyOf": { "$ref": "#/definitions/schemaArray" }, + "oneOf": { "$ref": "#/definitions/schemaArray" }, + "not": { "$ref": "#" } + }, + "default": true + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js +var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const discriminator_1 = require_discriminator(); + const draft7MetaSchema = require_json_schema_draft_07(); + const META_SUPPORT_DATA = ["/properties"]; + const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; + var Ajv = class extends core_1.default { + _addVocabularies() { + super._addVocabularies(); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + if (!this.opts.meta) return; + const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; + this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv = Ajv; + module.exports = exports = Ajv; + module.exports.Ajv = Ajv; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js +var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicAnchor = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const compile_1 = require_compile(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicAnchor", + schemaType: "string", + code: (cxt) => dynamicAnchor(cxt, cxt.schema) + }; + function dynamicAnchor(cxt, anchor) { + const { gen, it } = cxt; + it.schemaEnv.root.dynamicAnchors[anchor] = true; + const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; + const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); + gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); + } + exports.dynamicAnchor = dynamicAnchor; + function _getValidate(cxt) { + const { schemaEnv, schema, self } = cxt.it; + const { root, baseId, localRefs, meta } = schemaEnv.root; + const { schemaId } = self.opts; + const sch = new compile_1.SchemaEnv({ + schema, + schemaId, + root, + baseId, + localRefs, + meta + }); + compile_1.compileSchema.call(self, sch); + return (0, ref_1.getValidate)(cxt, sch); + } + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js +var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.dynamicRef = void 0; + const codegen_1 = require_codegen(); + const names_1 = require_names(); + const ref_1 = require_ref(); + const def = { + keyword: "$dynamicRef", + schemaType: "string", + code: (cxt) => dynamicRef(cxt, cxt.schema) + }; + function dynamicRef(cxt, ref) { + const { gen, keyword, it } = cxt; + if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); + const anchor = ref.slice(1); + if (it.allErrors) _dynamicRef(); + else { + const valid = gen.let("valid", false); + _dynamicRef(valid); + cxt.ok(valid); + } + function _dynamicRef(valid) { + if (it.schemaEnv.root.dynamicAnchors[anchor]) { + const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); + gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); + } else _callRef(it.validateName, valid)(); + } + function _callRef(validate, valid) { + return valid ? () => gen.block(() => { + (0, ref_1.callRef)(cxt, validate); + gen.let(valid, true); + }) : () => (0, ref_1.callRef)(cxt, validate); + } + } + exports.dynamicRef = dynamicRef; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js +var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const util_1 = require_util(); + const def = { + keyword: "$recursiveAnchor", + schemaType: "boolean", + code(cxt) { + if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); + else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js +var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicRef_1 = require_dynamicRef(); + const def = { + keyword: "$recursiveRef", + schemaType: "string", + code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js +var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dynamicAnchor_1 = require_dynamicAnchor(); + const dynamicRef_1 = require_dynamicRef(); + const recursiveAnchor_1 = require_recursiveAnchor(); + const recursiveRef_1 = require_recursiveRef(); + const dynamic = [ + dynamicAnchor_1.default, + dynamicRef_1.default, + recursiveAnchor_1.default, + recursiveRef_1.default + ]; + exports.default = dynamic; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js +var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentRequired", + type: "object", + schemaType: "object", + error: dependencies_1.error, + code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js +var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependencies_1 = require_dependencies(); + const def = { + keyword: "dependentSchemas", + type: "object", + schemaType: "object", + code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js +var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const util_1 = require_util(); + const def = { + keyword: ["maxContains", "minContains"], + type: "array", + schemaType: "number", + code({ keyword, parentSchema, it }) { + if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js +var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const dependentRequired_1 = require_dependentRequired(); + const dependentSchemas_1 = require_dependentSchemas(); + const limitContains_1 = require_limitContains(); + const next = [ + dependentRequired_1.default, + dependentSchemas_1.default, + limitContains_1.default + ]; + exports.default = next; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js +var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const names_1 = require_names(); + const def = { + keyword: "unevaluatedProperties", + type: "object", + schemaType: ["boolean", "object"], + trackErrors: true, + error: { + message: "must NOT have unevaluated properties", + params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` + }, + code(cxt) { + const { gen, schema, data, errsCount, it } = cxt; + /* istanbul ignore if */ + if (!errsCount) throw new Error("ajv implementation error"); + const { allErrors, props } = it; + if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); + else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); + it.props = true; + cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); + function unevaluatedPropCode(key) { + if (schema === false) { + cxt.setParams({ unevaluatedProperty: key }); + cxt.error(); + if (!allErrors) gen.break(); + return; + } + if (!(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.name("valid"); + cxt.subschema({ + keyword: "unevaluatedProperties", + dataProp: key, + dataPropType: util_1.Type.Str + }, valid); + if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + } + } + function unevaluatedDynamic(evaluatedProps, key) { + return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; + } + function unevaluatedStatic(evaluatedProps, key) { + const ps = []; + for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); + return (0, codegen_1.and)(...ps); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js +var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const codegen_1 = require_codegen(); + const util_1 = require_util(); + const def = { + keyword: "unevaluatedItems", + type: "array", + schemaType: ["boolean", "object"], + error: { + message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, + params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` + }, + code(cxt) { + const { gen, schema, data, it } = cxt; + const items = it.items || 0; + if (items === true) return; + const len = gen.const("len", (0, codegen_1._)`${data}.length`); + if (schema === false) { + cxt.setParams({ len: items }); + cxt.fail((0, codegen_1._)`${len} > ${items}`); + } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { + const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); + gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); + cxt.ok(valid); + } + it.items = true; + function validateItems(valid, from) { + gen.forRange("i", from, len, (i) => { + cxt.subschema({ + keyword: "unevaluatedItems", + dataProp: i, + dataPropType: util_1.Type.Num + }, valid); + if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); + }); + } + } + }; + exports.default = def; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js +var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const unevaluatedProperties_1 = require_unevaluatedProperties(); + const unevaluatedItems_1 = require_unevaluatedItems(); + const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; + exports.default = unevaluated; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json +var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/schema", + "$vocabulary": { + "https://json-schema.org/draft/2019-09/vocab/core": true, + "https://json-schema.org/draft/2019-09/vocab/applicator": true, + "https://json-schema.org/draft/2019-09/vocab/validation": true, + "https://json-schema.org/draft/2019-09/vocab/meta-data": true, + "https://json-schema.org/draft/2019-09/vocab/format": false, + "https://json-schema.org/draft/2019-09/vocab/content": true + }, + "$recursiveAnchor": true, + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "properties": { + "definitions": { + "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", + "type": "object", + "additionalProperties": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "meta/validation#/$defs/stringArray" }] } + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json +var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, + "$recursiveAnchor": true, + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "additionalItems": { "$recursiveRef": "#" }, + "unevaluatedItems": { "$recursiveRef": "#" }, + "items": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "#/$defs/schemaArray" }] }, + "contains": { "$recursiveRef": "#" }, + "additionalProperties": { "$recursiveRef": "#" }, + "unevaluatedProperties": { "$recursiveRef": "#" }, + "properties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" } + }, + "propertyNames": { "$recursiveRef": "#" }, + "if": { "$recursiveRef": "#" }, + "then": { "$recursiveRef": "#" }, + "else": { "$recursiveRef": "#" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$recursiveRef": "#" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$recursiveRef": "#" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json +var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, + "$recursiveAnchor": true, + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentMediaType": { "type": "string" }, + "contentEncoding": { "type": "string" }, + "contentSchema": { "$recursiveRef": "#" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json +var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, + "$recursiveAnchor": true, + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "type": "string", + "format": "uri-reference", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { + "type": "string", + "format": "uri" + }, + "$anchor": { + "type": "string", + "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" + }, + "$ref": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveRef": { + "type": "string", + "format": "uri-reference" + }, + "$recursiveAnchor": { + "type": "boolean", + "default": false + }, + "$vocabulary": { + "type": "object", + "propertyNames": { + "type": "string", + "format": "uri" + }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$recursiveRef": "#" }, + "default": {} + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json +var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/format", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, + "$recursiveAnchor": true, + "title": "Format vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json +var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, + "$recursiveAnchor": true, + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json +var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2019-09/schema", + "$id": "https://json-schema.org/draft/2019-09/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, + "$recursiveAnchor": true, + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js +var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema$1(); + const applicator = require_applicator$1(); + const content = require_content$1(); + const core = require_core$1(); + const format = require_format(); + const metadata = require_meta_data$1(); + const validation = require_validation$1(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2019($data) { + [ + metaSchema, + applicator, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2019; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js +var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; + const core_1 = require_core$3(); + const draft7_1 = require_draft7(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const discriminator_1 = require_discriminator(); + const json_schema_2019_09_1 = require_json_schema_2019_09(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; + var Ajv2019 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + this.addVocabulary(dynamic_1.default); + draft7_1.default.forEach((v) => this.addVocabulary(v)); + this.addVocabulary(next_1.default); + this.addVocabulary(unevaluated_1.default); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2019_09_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2019 = Ajv2019; + module.exports = exports = Ajv2019; + module.exports.Ajv2019 = Ajv2019; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2019; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js +var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const core_1 = require_core$2(); + const validation_1 = require_validation$2(); + const applicator_1 = require_applicator$2(); + const dynamic_1 = require_dynamic(); + const next_1 = require_next(); + const unevaluated_1 = require_unevaluated$1(); + const format_1 = require_format$1(); + const metadata_1 = require_metadata(); + const draft2020Vocabularies = [ + dynamic_1.default, + core_1.default, + validation_1.default, + (0, applicator_1.default)(true), + format_1.default, + metadata_1.metadataVocabulary, + metadata_1.contentVocabulary, + next_1.default, + unevaluated_1.default + ]; + exports.default = draft2020Vocabularies; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json +var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/schema", + "$vocabulary": { + "https://json-schema.org/draft/2020-12/vocab/core": true, + "https://json-schema.org/draft/2020-12/vocab/applicator": true, + "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, + "https://json-schema.org/draft/2020-12/vocab/validation": true, + "https://json-schema.org/draft/2020-12/vocab/meta-data": true, + "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, + "https://json-schema.org/draft/2020-12/vocab/content": true + }, + "$dynamicAnchor": "meta", + "title": "Core and Validation specifications meta-schema", + "allOf": [ + { "$ref": "meta/core" }, + { "$ref": "meta/applicator" }, + { "$ref": "meta/unevaluated" }, + { "$ref": "meta/validation" }, + { "$ref": "meta/meta-data" }, + { "$ref": "meta/format-annotation" }, + { "$ref": "meta/content" } + ], + "type": ["object", "boolean"], + "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", + "properties": { + "definitions": { + "$comment": "\"definitions\" has been replaced by \"$defs\".", + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "deprecated": true, + "default": {} + }, + "dependencies": { + "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", + "type": "object", + "additionalProperties": { "anyOf": [{ "$dynamicRef": "#meta" }, { "$ref": "meta/validation#/$defs/stringArray" }] }, + "deprecated": true, + "default": {} + }, + "$recursiveAnchor": { + "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", + "$ref": "meta/core#/$defs/anchorString", + "deprecated": true + }, + "$recursiveRef": { + "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", + "$ref": "meta/core#/$defs/uriReferenceString", + "deprecated": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json +var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/applicator", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, + "$dynamicAnchor": "meta", + "title": "Applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "prefixItems": { "$ref": "#/$defs/schemaArray" }, + "items": { "$dynamicRef": "#meta" }, + "contains": { "$dynamicRef": "#meta" }, + "additionalProperties": { "$dynamicRef": "#meta" }, + "properties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "patternProperties": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "propertyNames": { "format": "regex" }, + "default": {} + }, + "dependentSchemas": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" }, + "default": {} + }, + "propertyNames": { "$dynamicRef": "#meta" }, + "if": { "$dynamicRef": "#meta" }, + "then": { "$dynamicRef": "#meta" }, + "else": { "$dynamicRef": "#meta" }, + "allOf": { "$ref": "#/$defs/schemaArray" }, + "anyOf": { "$ref": "#/$defs/schemaArray" }, + "oneOf": { "$ref": "#/$defs/schemaArray" }, + "not": { "$dynamicRef": "#meta" } + }, + "$defs": { "schemaArray": { + "type": "array", + "minItems": 1, + "items": { "$dynamicRef": "#meta" } + } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json +var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, + "$dynamicAnchor": "meta", + "title": "Unevaluated applicator vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "unevaluatedItems": { "$dynamicRef": "#meta" }, + "unevaluatedProperties": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json +var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/content", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, + "$dynamicAnchor": "meta", + "title": "Content vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "contentEncoding": { "type": "string" }, + "contentMediaType": { "type": "string" }, + "contentSchema": { "$dynamicRef": "#meta" } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json +var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/core", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, + "$dynamicAnchor": "meta", + "title": "Core vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "$id": { + "$ref": "#/$defs/uriReferenceString", + "$comment": "Non-empty fragments not allowed.", + "pattern": "^[^#]*#?$" + }, + "$schema": { "$ref": "#/$defs/uriString" }, + "$ref": { "$ref": "#/$defs/uriReferenceString" }, + "$anchor": { "$ref": "#/$defs/anchorString" }, + "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, + "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, + "$vocabulary": { + "type": "object", + "propertyNames": { "$ref": "#/$defs/uriString" }, + "additionalProperties": { "type": "boolean" } + }, + "$comment": { "type": "string" }, + "$defs": { + "type": "object", + "additionalProperties": { "$dynamicRef": "#meta" } + } + }, + "$defs": { + "anchorString": { + "type": "string", + "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" + }, + "uriString": { + "type": "string", + "format": "uri" + }, + "uriReferenceString": { + "type": "string", + "format": "uri-reference" + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json +var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, + "$dynamicAnchor": "meta", + "title": "Format vocabulary meta-schema for annotation results", + "type": ["object", "boolean"], + "properties": { "format": { "type": "string" } } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json +var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, + "$dynamicAnchor": "meta", + "title": "Meta-data vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "title": { "type": "string" }, + "description": { "type": "string" }, + "default": true, + "deprecated": { + "type": "boolean", + "default": false + }, + "readOnly": { + "type": "boolean", + "default": false + }, + "writeOnly": { + "type": "boolean", + "default": false + }, + "examples": { + "type": "array", + "items": true + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json +var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { + module.exports = { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://json-schema.org/draft/2020-12/meta/validation", + "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, + "$dynamicAnchor": "meta", + "title": "Validation vocabulary meta-schema", + "type": ["object", "boolean"], + "properties": { + "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { + "type": "array", + "items": { "$ref": "#/$defs/simpleTypes" }, + "minItems": 1, + "uniqueItems": true + }] }, + "const": true, + "enum": { + "type": "array", + "items": true + }, + "multipleOf": { + "type": "number", + "exclusiveMinimum": 0 + }, + "maximum": { "type": "number" }, + "exclusiveMaximum": { "type": "number" }, + "minimum": { "type": "number" }, + "exclusiveMinimum": { "type": "number" }, + "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, + "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "pattern": { + "type": "string", + "format": "regex" + }, + "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, + "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "uniqueItems": { + "type": "boolean", + "default": false + }, + "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, + "minContains": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 1 + }, + "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, + "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, + "required": { "$ref": "#/$defs/stringArray" }, + "dependentRequired": { + "type": "object", + "additionalProperties": { "$ref": "#/$defs/stringArray" } + } + }, + "$defs": { + "nonNegativeInteger": { + "type": "integer", + "minimum": 0 + }, + "nonNegativeIntegerDefault0": { + "$ref": "#/$defs/nonNegativeInteger", + "default": 0 + }, + "simpleTypes": { "enum": [ + "array", + "boolean", + "integer", + "null", + "number", + "object", + "string" + ] }, + "stringArray": { + "type": "array", + "items": { "type": "string" }, + "uniqueItems": true, + "default": [] + } + } + }; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js +var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const metaSchema = require_schema(); + const applicator = require_applicator(); + const unevaluated = require_unevaluated(); + const content = require_content(); + const core = require_core(); + const format = require_format_annotation(); + const metadata = require_meta_data(); + const validation = require_validation(); + const META_SUPPORT_DATA = ["/properties"]; + function addMetaSchema2020($data) { + [ + metaSchema, + applicator, + unevaluated, + content, + core, + with$data(this, format), + metadata, + with$data(this, validation) + ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); + return this; + function with$data(ajv, sch) { + return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; + } + } + exports.default = addMetaSchema2020; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js +var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; + const core_1 = require_core$3(); + const draft2020_1 = require_draft2020(); + const discriminator_1 = require_discriminator(); + const json_schema_2020_12_1 = require_json_schema_2020_12(); + const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; + var Ajv2020 = class extends core_1.default { + constructor(opts = {}) { + super({ + ...opts, + dynamicRef: true, + next: true, + unevaluated: true + }); + } + _addVocabularies() { + super._addVocabularies(); + draft2020_1.default.forEach((v) => this.addVocabulary(v)); + if (this.opts.discriminator) this.addKeyword(discriminator_1.default); + } + _addDefaultMetaSchema() { + super._addDefaultMetaSchema(); + const { $data, meta } = this.opts; + if (!meta) return; + json_schema_2020_12_1.default.call(this, $data); + this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; + } + defaultMeta() { + return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); + } + }; + exports.Ajv2020 = Ajv2020; + module.exports = exports = Ajv2020; + module.exports.Ajv2020 = Ajv2020; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = Ajv2020; + var validate_1 = require_validate(); + Object.defineProperty(exports, "KeywordCxt", { + enumerable: true, + get: function() { + return validate_1.KeywordCxt; + } + }); + var codegen_1 = require_codegen(); + Object.defineProperty(exports, "_", { + enumerable: true, + get: function() { + return codegen_1._; + } + }); + Object.defineProperty(exports, "str", { + enumerable: true, + get: function() { + return codegen_1.str; + } + }); + Object.defineProperty(exports, "stringify", { + enumerable: true, + get: function() { + return codegen_1.stringify; + } + }); + Object.defineProperty(exports, "nil", { + enumerable: true, + get: function() { + return codegen_1.nil; + } + }); + Object.defineProperty(exports, "Name", { + enumerable: true, + get: function() { + return codegen_1.Name; + } + }); + Object.defineProperty(exports, "CodeGen", { + enumerable: true, + get: function() { + return codegen_1.CodeGen; + } + }); + var validation_error_1 = require_validation_error(); + Object.defineProperty(exports, "ValidationError", { + enumerable: true, + get: function() { + return validation_error_1.default; + } + }); + var ref_error_1 = require_ref_error(); + Object.defineProperty(exports, "MissingRefError", { + enumerable: true, + get: function() { + return ref_error_1.default; + } + }); +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js +var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; + function fmtDef(validate, compare) { + return { + validate, + compare + }; + } + exports.fullFormats = { + date: fmtDef(date, compareDate), + time: fmtDef(getTime(true), compareTime), + "date-time": fmtDef(getDateTime(true), compareDateTime), + "iso-time": fmtDef(getTime(), compareIsoTime), + "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), + duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, + uri, + "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, + "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, + url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, + email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, + hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, + ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, + ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, + regex, + uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, + "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, + "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, + "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, + byte, + int32: { + type: "number", + validate: validateInt32 + }, + int64: { + type: "number", + validate: validateInt64 + }, + float: { + type: "number", + validate: validateNumber + }, + double: { + type: "number", + validate: validateNumber + }, + password: true, + binary: true + }; + exports.fastFormats = { + ...exports.fullFormats, + date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), + time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), + "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), + "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), + "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), + uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, + "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, + email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i + }; + exports.formatNames = Object.keys(exports.fullFormats); + function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); + } + const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; + const DAYS = [ + 0, + 31, + 28, + 31, + 30, + 31, + 30, + 31, + 31, + 30, + 31, + 30, + 31 + ]; + function date(str) { + const matches = DATE.exec(str); + if (!matches) return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); + } + function compareDate(d1, d2) { + if (!(d1 && d2)) return void 0; + if (d1 > d2) return 1; + if (d1 < d2) return -1; + return 0; + } + const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; + function getTime(strictTimeZone) { + return function time(str) { + const matches = TIME.exec(str); + if (!matches) return false; + const hr = +matches[1]; + const min = +matches[2]; + const sec = +matches[3]; + const tz = matches[4]; + const tzSign = matches[5] === "-" ? -1 : 1; + const tzH = +(matches[6] || 0); + const tzM = +(matches[7] || 0); + if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; + if (hr <= 23 && min <= 59 && sec < 60) return true; + const utcMin = min - tzM * tzSign; + const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); + return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; + }; + } + function compareTime(s1, s2) { + if (!(s1 && s2)) return void 0; + const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); + const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); + if (!(t1 && t2)) return void 0; + return t1 - t2; + } + function compareIsoTime(t1, t2) { + if (!(t1 && t2)) return void 0; + const a1 = TIME.exec(t1); + const a2 = TIME.exec(t2); + if (!(a1 && a2)) return void 0; + t1 = a1[1] + a1[2] + a1[3]; + t2 = a2[1] + a2[2] + a2[3]; + if (t1 > t2) return 1; + if (t1 < t2) return -1; + return 0; + } + const DATE_TIME_SEPARATOR = /t|\s/i; + function getDateTime(strictTimeZone) { + const time = getTime(strictTimeZone); + return function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); + }; + } + function compareDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const d1 = new Date(dt1).valueOf(); + const d2 = new Date(dt2).valueOf(); + if (!(d1 && d2)) return void 0; + return d1 - d2; + } + function compareIsoDateTime(dt1, dt2) { + if (!(dt1 && dt2)) return void 0; + const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); + const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); + const res = compareDate(d1, d2); + if (res === void 0) return void 0; + return res || compareTime(t1, t2); + } + const NOT_URI_FRAGMENT = /\/|:/; + const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; + function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI.test(str); + } + const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; + function byte(str) { + BYTE.lastIndex = 0; + return BYTE.test(str); + } + const MIN_INT32 = -(2 ** 31); + const MAX_INT32 = 2 ** 31 - 1; + function validateInt32(value) { + return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; + } + function validateInt64(value) { + return Number.isInteger(value); + } + function validateNumber() { + return true; + } + const Z_ANCHOR = /[^\\]\\Z/; + function regex(str) { + if (Z_ANCHOR.test(str)) return false; + try { + new RegExp(str); + return true; + } catch (e) { + return false; + } + } +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js +var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.formatLimitDefinition = void 0; + const ajv_1 = require_ajv(); + const codegen_1 = require_codegen(); + const ops = codegen_1.operators; + const KWDs = { + formatMaximum: { + okStr: "<=", + ok: ops.LTE, + fail: ops.GT + }, + formatMinimum: { + okStr: ">=", + ok: ops.GTE, + fail: ops.LT + }, + formatExclusiveMaximum: { + okStr: "<", + ok: ops.LT, + fail: ops.GTE + }, + formatExclusiveMinimum: { + okStr: ">", + ok: ops.GT, + fail: ops.LTE + } + }; + const error = { + message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, + params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` + }; + exports.formatLimitDefinition = { + keyword: Object.keys(KWDs), + type: "string", + schemaType: "string", + $data: true, + error, + code(cxt) { + const { gen, data, schemaCode, keyword, it } = cxt; + const { opts, self } = it; + if (!opts.validateFormats) return; + const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); + if (fCxt.$data) validate$DataFormat(); + else validateFormat(); + function validate$DataFormat() { + const fmts = gen.scopeValue("formats", { + ref: self.formats, + code: opts.code.formats + }); + const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); + cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); + } + function validateFormat() { + const format = fCxt.schema; + const fmtDef = self.formats[format]; + if (!fmtDef || fmtDef === true) return; + if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); + const fmt = gen.scopeValue("formats", { + key: format, + ref: fmtDef, + code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 + }); + cxt.fail$data(compareCode(fmt)); + } + function compareCode(fmt) { + return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; + } + }, + dependencies: ["format"] + }; + const formatLimitPlugin = (ajv) => { + ajv.addKeyword(exports.formatLimitDefinition); + return ajv; + }; + exports.default = formatLimitPlugin; +})); + +//#endregion +//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js +var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { + Object.defineProperty(exports, "__esModule", { value: true }); + const formats_1 = require_formats(); + const limit_1 = require_limit(); + const codegen_1 = require_codegen(); + const fullName = new codegen_1.Name("fullFormats"); + const fastName = new codegen_1.Name("fastFormats"); + const formatsPlugin = (ajv, opts = { keywords: true }) => { + if (Array.isArray(opts)) { + addFormats(ajv, opts, formats_1.fullFormats, fullName); + return ajv; + } + const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; + addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); + if (opts.keywords) (0, limit_1.default)(ajv); + return ajv; + }; + formatsPlugin.get = (name, mode = "full") => { + const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; + if (!f) throw new Error(`Unknown format "${name}"`); + return f; + }; + function addFormats(ajv, list, fs, exportName) { + var _a; + var _b; + (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); + for (const f of list) ajv.addFormat(f, fs[f]); + } + module.exports = exports = formatsPlugin; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.default = formatsPlugin; +})); + +//#endregion +//#region ../core-internal/src/validators/ajvProvider.ts +var import_ajv = require_ajv(); +var import__2019 = require__2019(); +var import__2020 = require__2020(); +var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); +/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ +const ajvProvider_CEoC_sr_addFormats = import_dist.default; +function createDefaultAjvInstance(engineClass) { + const ajv = new engineClass({ + strict: false, + validateFormats: true, + validateSchema: false, + allErrors: true + }); + ajvProvider_CEoC_sr_addFormats(ajv); + return ajv; +} +/** +* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` +* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). +* +* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` +* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class +* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv +* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching +* v1's default engine), while the cfworker provider ignores them per spec. +* Schemas declaring any other `$schema` are +* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate +* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type +* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 +* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and +* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would +* silently downgrade dialect. +* +* @example Use with default configuration +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" +* const validator = new AjvJsonSchemaValidator(); +* ``` +* +* @example Use with a custom AJV instance +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +* +* @example Register ajv-formats +* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" +* // import { Ajv2020 } from 'ajv/dist/2020.js'; +* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* const validator = new AjvJsonSchemaValidator(ajv); +* ``` +*/ +var AjvJsonSchemaValidator = class { + _ajv; + /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ + _ajvDraft7; + /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ + _ajv2019; + /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ + _userAjv; + /** + * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is + * used for **every** schema regardless of its declared `$schema` (the caller owns dialect + * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, + * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with + * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and + * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so + * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never + * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter + * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. + */ + constructor(ajv) { + this._userAjv = ajv !== void 0; + this._ajv = ajv; + } + /** The underlying 2020-12 engine — the default instance is created on first use. */ + get ajv() { + return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); + } + /** + * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for + * every schema — do not second-guess by `$schema` (bring-your-own-validator means + * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → + * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. + */ + _engineFor(schema) { + if (this._userAjv) return this.ajv; + const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); + if (dialect === "2020-12") return this.ajv; + if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); + return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); + } + getValidator(schema) { + const engine = this._engineFor(schema); + const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); + return (input) => { + return ajvValidator(input) ? { + valid: true, + data: input, + errorMessage: void 0 + } : { + valid: false, + data: void 0, + errorMessage: engine.errorsText(ajvValidator.errors) + }; + }; + } +}; +/** +* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. +* The full v1-equivalent construction is: +* +* ```ts +* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); +* addFormats(ajv); +* new AjvJsonSchemaValidator(ajv); +* ``` +* +* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque +* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` +* validation that the v1 default had). +* +* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream +* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own +* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. +*/ +const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; + +//#endregion + +//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map + + + + + + + + +//#region src/server/completable.ts +const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); +/** +* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. +* +* @example +* ```ts source="./completable.examples.ts#completable_basicUsage" +* server.registerPrompt( +* 'review-code', +* { +* title: 'Code Review', +* argsSchema: z.object({ +* language: completable(z.string().describe('Programming language'), value => +* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) +* ) +* }) +* }, +* ({ language }) => ({ +* messages: [ +* { +* role: 'user' as const, +* content: { +* type: 'text' as const, +* text: `Review this ${language} code.` +* } +* } +* ] +* }) +* ); +* ``` +* +* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions +*/ +function completable(schema, complete) { + Object.defineProperty(schema, COMPLETABLE_SYMBOL, { + value: { complete }, + enumerable: false, + writable: false, + configurable: false + }); + return schema; +} +/** +* Checks if a schema is completable (has completion metadata). +*/ +function isCompletable(schema) { + return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; +} +/** +* Gets the completer callback from a completable schema, if it exists. +*/ +function getCompleter(schema) { + return schema[COMPLETABLE_SYMBOL]?.complete; +} + +//#endregion +//#region src/server/sseKeepAlive.ts +/** Default interval between SSE keep-alive comment frames. */ +const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; +const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); +/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ +function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { + if (!Number.isFinite(intervalMs) || intervalMs < 1) return; + const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); + timer.unref?.(); + return timer; +} + +//#endregion +//#region src/server/serverEventBus.ts +/** +* A `ServerEventBus` backed by an in-process listener set. +* +* `publish()` delivers synchronously to the live listener set (a listener +* unsubscribing itself mid-dispatch is safe; the entry's listen-router +* listeners never unsubscribe peers). A throwing listener does not stop +* delivery to the others. +*/ +var mcp_DXXb3Vv3_InMemoryServerEventBus = class { + _listeners = /* @__PURE__ */ new Set(); + /** + * @param onerror - Optional callback for errors thrown by listeners + * during dispatch. + */ + constructor(onerror) { + this.onerror = onerror; + } + publish(event) { + for (const listener of this._listeners) try { + listener(event); + } catch (error) { + this.onerror?.(error instanceof Error ? error : new Error(String(error))); + } + } + subscribe(listener) { + this._listeners.add(listener); + let live = true; + return () => { + if (!live) return; + live = false; + this._listeners.delete(listener); + }; + } + /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ + get listenerCount() { + return this._listeners.size; + } +}; +/** Build a {@linkcode ServerNotifier} over a bus. */ +function mcp_DXXb3Vv3_createServerNotifier(bus) { + return { + toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), + promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), + resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), + resourceUpdated: (uri) => bus.publish({ + kind: "resource_updated", + uri + }) + }; +} +/** +* Whether a `subscriptions/listen` filter accepts a given change event. +* +* Pure: no I/O, no mutation. The filter governs ONLY the four +* subscription-gated change types — non-gated notifications never reach the +* bus and are not modeled here. +* +* `resource_updated` matches only when `resourceSubscriptions` is present and +* contains the event's URI exactly (per the spec: "for these resource URIs"). +*/ +function listenFilterAccepts(filter, event) { + switch (event.kind) { + case "tools_list_changed": return filter.toolsListChanged === true; + case "prompts_list_changed": return filter.promptsListChanged === true; + case "resources_list_changed": return filter.resourcesListChanged === true; + case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); + } +} +/** +* The honored subset of a requested filter: keeps only the fields the client +* explicitly opted in to (drops `false` and absent fields), narrowed against +* the server's declared capabilities when supplied. The serving entry sends +* this back in `notifications/subscriptions/acknowledged` so the ack reflects +* what the server can actually deliver. +* +* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` +* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. +* - `resourceSubscriptions` is honored only when +* `capabilities.resources.subscribe` is advertised. +* +* `capabilities` is optional on this pure helper for test convenience only — +* both wired routers REQUIRE capabilities at the call site (the HTTP router's +* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws +* before `setServerCapabilities()` was called), so the fail-open +* `undefined → honor everything` branch is never reachable on a wired entry. +*/ +function honoredSubset(requested, capabilities) { + const honored = {}; + const allow = (bit) => capabilities === void 0 || bit === true; + if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; + if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; + if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; + if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; + return honored; +} +/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ +function serverEventToNotification(event) { + switch (event.kind) { + case "tools_list_changed": return { method: "notifications/tools/list_changed" }; + case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; + case "resources_list_changed": return { method: "notifications/resources/list_changed" }; + case "resource_updated": return { + method: "notifications/resources/updated", + params: { uri: event.uri } + }; + } +} + +//#endregion +//#region src/server/listenRouter.ts +/** Default capacity guard: refuse a new subscription when this many are already open. */ +const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; +function jsonRpcError(id, code, message) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message + }, + id + }, { status: 200 }); +} +/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ +function stampSubscriptionId(notification, subscriptionId) { + return { + method: notification.method, + params: { + ...notification.params, + _meta: { + ...notification.params?._meta, + [SUBSCRIPTION_ID_META_KEY]: subscriptionId + } + } + }; +} +/** +* Read the requested filter off a `subscriptions/listen` request body. +* Returns the validated filter, or `undefined` when `params.notifications` +* is absent or fails the schema (the caller answers `-32602` — the spec +* marks `notifications` REQUIRED on the listen request). +*/ +function parseListenFilter(message) { + const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); + return outcome.ok ? outcome.value.params?.notifications : void 0; +} +function mcp_DXXb3Vv3_createListenRouter(options) { + const { bus, onerror } = options; + const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; + const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; + const open = /* @__PURE__ */ new Set(); + function serve(message, signal, capabilities, serverInfo) { + if (open.size >= maxSubscriptions) { + onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); + return jsonRpcError(message.id, -32603, "Subscription limit reached"); + } + const filter = parseListenFilter(message); + if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); + const honored = honoredSubset(filter, capabilities); + const subscriptionId = message.id; + const encoder = new TextEncoder(); + let controller; + let closed = false; + let unsubscribe; + let keepAliveTimer; + let abortCleanup; + const writeFrame = (frame) => { + if (closed) return; + try { + controller.enqueue(encoder.encode(frame)); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + }; + const writeNotification = (method, params) => { + writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + method, + params + })}\n\n`); + }; + const teardown = (graceful) => { + if (closed) return; + if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ + jsonrpc: "2.0", + id: subscriptionId, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: subscriptionId, + [SERVER_INFO_META_KEY]: serverInfo + } + } + })}\n\n`); + closed = true; + try { + unsubscribe?.(); + } catch (error) { + onerror?.(error instanceof Error ? error : new Error(String(error))); + } + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + abortCleanup?.(); + open.delete(teardown); + try { + controller.close(); + } catch {} + }; + const readable = new ReadableStream({ + start(streamController) { + controller = streamController; + const ack = stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, subscriptionId); + writeNotification(ack.method, ack.params); + unsubscribe = bus.subscribe((event) => { + if (closed || !listenFilterAccepts(honored, event)) return; + const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); + writeNotification(note.method, note.params); + }); + keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); + open.add(teardown); + }, + cancel() { + teardown(false); + } + }); + if (signal !== void 0) if (signal.aborted) teardown(false); + else { + const onAbort = () => teardown(false); + signal.addEventListener("abort", onAbort, { once: true }); + abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + return new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + }); + } + return { + serve, + closeAll() { + for (const teardown of open) teardown(true); + }, + get openCount() { + return open.size; + } + }; +} +const CHANGE_NOTIFICATION_METHODS = new Set([ + "notifications/tools/list_changed", + "notifications/prompts/list_changed", + "notifications/resources/list_changed", + "notifications/resources/updated" +]); +/** +* Per-connection listen state for the stdio entry. One instance is held by +* `serveStdio` for the connection lifetime; it routes inbound +* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound +* change notifications onto the active subscriptions. No bus — the long-lived +* pinned instance's existing `send*ListChanged()` calls feed straight into +* `routeOutbound()`. +*/ +var mcp_DXXb3Vv3_StdioListenRouter = class { + /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ + _subs = /* @__PURE__ */ new Map(); + /** + * The serving instance's declared capabilities. Filled in by the entry + * once the modern instance is constructed (the router is created before + * the instance exists), so the acknowledged filter is narrowed against + * what the server can actually deliver. + */ + _serverCapabilities; + /** + * The serving instance's identity, stamped onto the graceful-close + * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends + * `ResultMetaObject`). Handed over together with the capabilities. + */ + _serverInfo; + constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { + this._maxSubscriptions = _maxSubscriptions; + this._serverCapabilities = serverCapabilities; + this._serverInfo = serverInfo; + } + /** + * Record the serving instance's declared capabilities and identity once + * it has been constructed. Called by `serveStdio`'s connect path; + * subsequent `serve()` calls narrow the honored filter against the + * capabilities, and `teardownAll()` stamps the identity. + */ + setServerCapabilities(capabilities, serverInfo) { + this._serverCapabilities = capabilities; + if (serverInfo !== void 0) this._serverInfo = serverInfo; + } + /** Whether `id` is an active listen subscription on this connection. */ + has(id) { + return this._subs.has(id); + } + /** + * Serve one inbound `subscriptions/listen` request: registers the + * subscription and returns the stamped acknowledged notification (or, on + * capacity / params rejection, the in-band JSON-RPC error response). + * + * @throws when called before {@linkcode setServerCapabilities} (or the + * constructor) has supplied the serving instance's capabilities. Honoring a + * filter without knowing the server's advertised capabilities would fail + * open (deliver unadvertised types); the entry guarantees capabilities are + * set before any listen request is routed here. + */ + serve(message) { + if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); + if (this._subs.size >= this._maxSubscriptions) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32603, + message: "Subscription limit reached" + } + }; + const filter = parseListenFilter(message); + if (filter === void 0) return { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" + } + }; + const honored = honoredSubset(filter, this._serverCapabilities); + this._subs.set(message.id, honored); + return stampSubscriptionId({ + method: "notifications/subscriptions/acknowledged", + params: { notifications: honored } + }, message.id); + } + /** + * Tear down one subscription (inbound `notifications/cancelled`). Returns + * `true` when a subscription was removed. After this call NOTHING further + * is delivered for that subscription id (the post-cancel hardening). + */ + cancel(id) { + return this._subs.delete(id); + } + /** + * Route an outbound notification through the active subscriptions. + * + * - For a subscription-gated change notification, returns one stamped copy + * per subscription that opted in to it (an empty array means it is + * dropped — the modern era never delivers an un-requested change type). + * - For any other outbound message, returns `'passthrough'` (the entry + * forwards it as-is). + */ + routeOutbound(message) { + if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; + const uriParam = message.params?.["uri"]; + const uri = typeof uriParam === "string" ? uriParam : void 0; + const event = notificationToServerEvent(message.method, uri); + const out = []; + for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ + method: message.method, + params: message.params ?? {} + }, subscriptionId)); + return out; + } + /** + * Server-side graceful teardown of every active subscription: returns the + * empty `subscriptions/listen` JSON-RPC result for each subscription id — + * the spec's graceful-close signal, `_meta` carrying the subscription id + * and the serving instance's identity — for the entry to emit before + * closing the wire. Clears the set so nothing further is delivered. + */ + teardownAll() { + const out = []; + for (const id of this._subs.keys()) out.push({ + jsonrpc: "2.0", + id, + result: { + resultType: "complete", + _meta: { + [SUBSCRIPTION_ID_META_KEY]: id, + ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } + } + } + }); + this._subs.clear(); + return out; + } +}; +function notificationToServerEvent(method, uri) { + switch (method) { + case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; + case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; + case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; + default: return { + kind: "resource_updated", + uri: uri ?? "" + }; + } +} + +//#endregion +//#region src/server/legacyInputRequiredShim.ts +/** +* Default handler re-entries per originating request — tighter than the +* client driver's 10 because the shim holds a live wire request open. +*/ +const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; +/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ +const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; +/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ +function resolveLegacyShimOptions(options) { + if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); + if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); + return { + maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, + roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, + legacyShim: options?.legacyShim ?? true + }; +} +/** +* Validates one `inputRequests` entry: malformed or unknown kinds are server +* bugs and fail loudly on both eras. Shared by the modern seam's capability +* check and the shim's gate. +*/ +function coerceEmbeddedInputRequest(method, key, entry) { + if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); + const embedded = entry; + const required = requiredClientCapabilitiesForInputRequest(embedded); + if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); + return { + embedded, + required + }; +} +/** +* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 +* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a +* getRandomValues fallback for runtimes without `randomUUID`). +*/ +function syntheticElicitationId() { + const webCrypto = globalThis.crypto; + if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); + const bytes = new Uint8Array(16); + webCrypto.getRandomValues(bytes); + bytes[6] = bytes[6] & 15 | 64; + bytes[8] = bytes[8] & 63 | 128; + const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} +/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ +function legacyShimFailure(method, message) { + if (method === "tools/call") return { + content: [{ + type: "text", + text: message + }], + isError: true + }; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); +} +/** The fulfilment loop — see the module doc for the contract. */ +var LegacyInputRequiredShim = class { + constructor(_host) { + this._host = _host; + } + async fulfill(method, handler, request, ctx, firstResult) { + const { maxRounds, roundTimeoutMs } = this._host; + const outerSignal = ctx.mcpReq.signal; + let current = firstResult; + let round = 0; + while (true) { + round += 1; + if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); + const inputRequests = current.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const requestState = typeof current.requestState === "string" ? current.requestState : void 0; + if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + let responses; + if (hasInputRequests) { + const declared = this._host.resolvedClientCapabilities(ctx); + const coerced = []; + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); + if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); + coerced.push([key, embedded]); + } + const roundAbort = linkedRoundAbort(outerSignal); + try { + const legOptions = { + relatedRequestId: ctx.mcpReq.id, + timeout: roundTimeoutMs, + resetTimeoutOnProgress: true, + onprogress: () => {}, + signal: roundAbort.signal + }; + const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { + try { + return [key, await this._dispatchLeg(embedded, legOptions)]; + } catch (error) { + roundAbort.abort(error); + throw error; + } + })); + responses = Object.fromEntries(fulfilled); + } catch (error) { + if (outerSignal.aborted) throw error; + return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); + } finally { + roundAbort.dispose(); + } + } else await sleep((/* inlined export .C */250), outerSignal); + let ctxNext = { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + inputResponses: responses, + droppedInputResponseKeys: void 0, + requestState: requestStateAccessor(requestState) + } + }; + if (requestState !== void 0) { + const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); + if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); + } + const next = await handler(request, ctxNext); + if (!isInputRequiredResult(next)) return next; + current = next; + } + } + /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ + async _dispatchLeg(embedded, options) { + switch (embedded.method) { + case "elicitation/create": { + let params = embedded.params; + if (params.mode === "url" && params.elicitationId === void 0) params = { + ...params, + elicitationId: syntheticElicitationId() + }; + return await this._host.sendElicitation(params, options); + } + case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); + case "roots/list": return await this._host.listRoots(embedded.params, options); + } + } +}; + +//#endregion +//#region src/server/server.ts +/** +* The request methods whose 2026-07-28 result vocabulary includes +* `input_required` (the multi round-trip methods). Returning an +* input-required result from any other handler is a server bug. +*/ +const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ + "tools/call", + "prompts/get", + "resources/read" +]); +let writeClientIdentity; +let installDiscoverHandler; +let readServerIdentity; +/** +* Package-internal: backfills the connection-scoped client-identity fields of a +* per-request server instance from the request's validated `_meta` envelope, so the +* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} +* accessors keep answering on instances that never see an `initialize` handshake. +* Not public API. +*/ +function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { + writeClientIdentity(server, identity); +} +/** +* Package-internal: installs the modern-only `server/discover` handler on an instance +* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern +* revisions the entry serves appear in the instance's supported-versions list (so the +* discover advertisement and version-mismatch errors name them). Idempotent. +* Hand-constructed instances are unaffected: nothing else calls this, so they keep +* answering `-32601` unless their own supported-versions list opts into a modern +* revision. Not public API. +*/ +function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { + installDiscoverHandler(server, servedModernVersions); +} +/** +* Package-internal: the instance's implementation identity, for the serving +* entries to stamp onto entry-built results (the `subscriptions/listen` +* graceful-close result — built outside the encode seam, but the spec's +* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries +* the serverInfo SHOULD like every other result). Not public API. +*/ +function mcp_DXXb3Vv3_serverIdentityOf(server) { + return readServerIdentity(server); +} +/** +* An MCP server on top of a pluggable transport. +* +* This server will automatically respond to the initialization flow as initiated from the client. +* +* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. +*/ +var Server = class extends Protocol { + _clientCapabilities; + _clientVersion; + static { + writeClientIdentity = (server, identity) => { + if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; + if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; + }; + installDiscoverHandler = (server, servedModernVersions) => { + const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); + if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; + server.setRequestHandler("server/discover", () => server._ondiscover()); + }; + readServerIdentity = (server) => server._serverInfo; + } + _capabilities; + _instructions; + _jsonSchemaValidator; + _cacheHints; + _requestStateVerify; + _inputRequiredServing; + _legacyShim; + /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ + _legacyInputRequiredShim() { + return this._legacyShim ??= new LegacyInputRequiredShim({ + maxRounds: this._inputRequiredServing.maxRounds, + roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, + resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), + verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), + sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), + sendSampling: (params, options) => this.createMessage(params, options), + listRoots: (params, options) => this.listRoots(params, options) + }); + } + /** + * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). + */ + oninitialized; + /** + * Initializes this server with the given name and version information. + */ + constructor(_serverInfo, options) { + super(options); + this._serverInfo = _serverInfo; + this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; + this._instructions = options?.instructions; + this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); + this._requestStateVerify = options?.requestState?.verify; + this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); + if (options?.cacheHints !== void 0) { + for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); + this._cacheHints = options.cacheHints; + } + this.setRequestHandler("initialize", (request) => this._oninitialize(request)); + this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); + if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); + if (this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Registers the built-in `logging/setLevel` request handler. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + _registerLoggingHandler() { + this.setRequestHandler("logging/setLevel", async (request, ctx) => { + const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; + const { level } = request.params; + const parseResult = parseSchema(LoggingLevelSchema, level); + if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); + return {}; + }); + } + buildContext(ctx, transportInfo) { + const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; + return { + ...ctx, + mcpReq: { + ...ctx.mcpReq, + log: (level, data, logger) => { + if (!this._capabilities.logging) return Promise.resolve(); + let threshold; + if (this._servedModernEra()) { + threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; + if (threshold === void 0) return Promise.resolve(); + } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); + if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); + return ctx.mcpReq.notify({ + method: "notifications/message", + params: { + level, + data, + logger + } + }); + }, + elicitInput: (params, options) => this.elicitInput(params, options), + requestSampling: (params, options) => this.createMessage(params, options) + }, + http: hasHttpInfo ? { + ...ctx.http, + req: transportInfo?.request, + closeSSE: transportInfo?.closeSSEStream, + closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream + } : void 0 + }; + } + _loggingLevels = /* @__PURE__ */ new Map(); + LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); + isMessageIgnored = (level, sessionId) => { + const currentLevel = this._loggingLevels.get(sessionId); + return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; + }; + /** + * Registers new capabilities. This can only be called before connecting to a transport. + * + * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). + */ + registerCapabilities(capabilities) { + if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); + const hadLogging = !!this._capabilities.logging; + this._capabilities = mergeCapabilities(this._capabilities, capabilities); + if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); + } + /** + * Enforces server-side validation for `tools/call` results regardless of how the + * handler was registered, attaches the configured per-operation cache hint + * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` + * for results that do not provide their own, and owns the multi-round-trip + * seam: on the methods whose 2026-07-28 result vocabulary includes + * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an + * input-required return skips result-schema validation and is checked + * against the served era, the at-least-one rule, and the request's own + * declared client capabilities; on every other method an input-required + * return is a server bug and fails loudly. The hint rides a symbol-keyed + * property that is never serialized, so 2025-era responses are unaffected. + */ + _wrapHandler(method, handler) { + if (method !== "tools/call") { + const cacheHint = this._cacheHints?.[method]; + const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); + if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { + const result = await handler(request, ctx); + if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + }; + return async (request, ctx) => { + const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); + if (isInputRequiredResult(result)) { + if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); + return result; + } + return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); + }; + } + return async (request, ctx) => { + const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); + const validatedRequest = codec.validateRequest("tools/call", request); + if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); + const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); + if (isInputRequiredResult(result)) return result; + const normalizedResult = normalizeContentlessToolResult(result); + const validationResult = codec.validateResult("tools/call", normalizedResult); + if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); + return validationResult.value; + }; + } + /** + * Whether this instance is bound to a 2026-07-28-or-later protocol + * revision. Era is instance state — a serving entry (`createMcpHandler`, + * `serveStdio`) marks the instance modern at construction; a 2025-era + * `initialize` handshake binds it legacy. The multi-round-trip seam reads + * this directly: there is no per-request era consult. + */ + _servedModernEra() { + return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); + } + /** + * Invokes a handler for one of the multi-round-trip methods and applies + * the input-required seam: + * + * - a `UrlElicitationRequiredError` (or any 2025-style server→client + * request idiom) escaping the handler on a request served on the + * 2026-07-28 era fails LOUDLY with a clear steer to + * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the + * 2026-07-28 wire and the throw is not silently converted. Requests + * served on the 2025 era keep today's `-32042` behavior byte-exact (the + * error is rethrown unchanged). + * - an input-required RETURN toward a 2026-07-28 request must satisfy + * the at-least-one rule, and every embedded request must be covered by + * the capabilities declared on the request's envelope (violations + * answer the typed `-32021` error). Toward a 2025-era request the + * return is fulfilled by the default-on legacy shim, whose own gate + * consults the initialize-declared capabilities and surfaces + * violations per family; `inputRequired.legacyShim: false` restores + * the pre-shim loud failure. + */ + async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { + const servedModern = this._servedModernEra(); + const rawRequestState = ctx.mcpReq.requestState(); + if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + let ctxForHandler = ctx; + if (typeof rawRequestState === "string") { + const decoded = await this._verifyRequestState(rawRequestState, ctx, method); + if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); + } + let result; + try { + result = await handler(request, ctxForHandler); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { + if (!servedModern) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); + } + throw error; + } + if (!isInputRequiredResult(result)) return result; + if (!servedModern) { + if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); + return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); + } + const inputRequests = result.inputRequests; + const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; + const hasRequestState = typeof result.requestState === "string"; + if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); + if (hasInputRequests) { + const declared = this._inputRequestCapabilityView(ctx); + for (const [key, entry] of Object.entries(inputRequests)) { + const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); + const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); + if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); + } + } + return result; + } + /** + * Runs the configured `requestState.verify` hook and returns its + * resolved value (`undefined` when unconfigured or the hook returns + * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; + * the reason goes to `onerror` only. + */ + async _verifyRequestState(state, ctx, method) { + if (this._requestStateVerify === void 0) return; + try { + return await this._requestStateVerify(state, ctx); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); + } + } + /** + * The per-request resolved client-capabilities view: the request's own + * `_meta` envelope on the 2026 era; the `initialize`-declared state on a + * 2025-era connection. Per-request instances that never saw an + * initialize (stateless legacy) hold nothing, so gates refuse there. + */ + _inputRequestCapabilityView(ctx) { + return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; + } + /** + * Guard for the push-style server→client request APIs ({@linkcode createMessage}, + * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a + * modern-era instance: the 2026-07-28 revision has no server→client request + * channel, so the call fails before any wire traffic with a typed error + * whose message steers to `inputRequired(...)`. The base era gate would + * also reject it; this guard runs first to carry the steer. + */ + _assertPushApiInServedEra(method) { + if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { + method, + era: "2026-07-28" + }); + } + assertCapabilityForMethod(method) { + switch (method) { + case "sampling/createMessage": + if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); + break; + case "elicitation/create": + if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); + break; + case "roots/list": + if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); + break; + case "ping": break; + } + } + assertNotificationCapability(method) { + switch (method) { + case "notifications/message": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "notifications/resources/updated": + case "notifications/resources/list_changed": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); + break; + case "notifications/tools/list_changed": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); + break; + case "notifications/prompts/list_changed": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); + break; + case "notifications/elicitation/complete": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); + break; + case "notifications/cancelled": break; + case "notifications/progress": break; + } + } + assertRequestHandlerCapability(method) { + switch (method) { + case "completion/complete": + if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); + break; + case "logging/setLevel": + if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); + break; + case "prompts/get": + case "prompts/list": + if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); + break; + case "resources/list": + case "resources/templates/list": + case "resources/read": + if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); + break; + case "tools/call": + case "tools/list": + if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); + break; + case "ping": + case "initialize": break; + } + } + async _oninitialize(request) { + const requestedVersion = request.params.protocolVersion; + this._clientCapabilities = request.params.capabilities; + this._clientVersion = request.params.clientInfo; + const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); + const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; + this._negotiatedProtocolVersion = protocolVersion; + this.transport?.setProtocolVersion?.(protocolVersion); + return { + protocolVersion, + capabilities: this.getCapabilities(), + serverInfo: this._serverInfo, + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` + * lists only modern revisions (2025-era versions are negotiated via `initialize`); + * the capabilities are advertised as-is, listChanged/subscribe bits included + * (see {@linkcode discoverAdvertisedCapabilities}). + */ + _ondiscover() { + return { + supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), + capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), + ...this._instructions && { instructions: this._instructions } + }; + } + /** + * The identity the 2026-era encode seam stamps into every outbound + * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR + * #3002: servers SHOULD identify themselves on every response). + */ + _outboundServerInfo() { + return this._serverInfo; + } + /** + * After initialization has completed, this will be populated with the client's reported capabilities. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * declared capabilities, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientCapabilities() { + return this._clientCapabilities; + } + /** + * After initialization has completed, this will be populated with information about the client's name and version. + * + * @deprecated Read client identity from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's + * name and version, while on 2025-era connections this accessor keeps returning the + * `initialize`-scoped value. The accessor remains functional — instances serving the + * 2026-07-28 era are backfilled per request from the validated envelope. + */ + getClientVersion() { + return this._clientVersion; + } + /** + * After initialization has completed, this will be populated with the protocol version negotiated + * with the client (the version the server responded with during the initialize handshake), or + * `undefined` before initialization. + * + * @deprecated Read the protocol revision from the per-request handler context instead: on + * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the + * request was sent for, while on 2025-era connections this accessor keeps returning the + * `initialize`-negotiated version. The accessor remains functional — instances serving the + * 2026-07-28 era report that revision. + */ + getNegotiatedProtocolVersion() { + return this._negotiatedProtocolVersion; + } + /** + * Project a `tools/call` result through this instance's negotiated wire + * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on + * the 2025 era the `{result:…}` wrap when `structuredContent` is a + * non-object value or the advertised `outputSchema` had a non-object root. + * Identity for object-shaped `structuredContent` on the 2026 era. + * + * `McpServer`'s built-in `tools/call` handler routes through this method. + * Low-level `setRequestHandler('tools/call', …)` authors call it + * themselves so the projection lives in one place (the codec) and the + * server-side handler stays era-blind. + * + * This is the only codec function exposed on `Server` — the full + * `WireCodec` is intentionally not part of the public surface. + */ + projectCallToolResult(result, advertisedOutputSchema) { + return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); + } + /** + * Returns the current server capabilities. + */ + getCapabilities() { + return this._capabilities; + } + /** + * Sends a `ping` request to the connected client. + * + * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. + * If your factory serves both eras, this only works on the legacy path. + */ + async ping() { + this._assertPushApiInServedEra("ping"); + return this.request({ method: "ping" }); + } + async createMessage(params, options) { + this._assertPushApiInServedEra("sampling/createMessage"); + if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); + if (params.messages.length > 0) { + const lastMessage = params.messages.at(-1); + const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; + const hasToolResults = lastContent.some((c) => c.type === "tool_result"); + const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; + const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; + const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); + if (hasToolResults) { + if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); + if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); + } + if (hasPreviousToolUse) { + const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); + const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); + if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); + } + } + const hasTools = Boolean(params.tools || params.toolChoice); + const wide = await this.request({ + method: "sampling/createMessage", + params + }, options); + const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); + if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); + return outcome.value; + } + /** + * Creates an elicitation request for the given parameters. + * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. + * @param params The parameters for the elicitation request. + * @param options Optional request options. + * @returns The result of the elicitation request. + * + * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) + * instead. The 2025 push-style server-to-client request model is replaced by input_required + * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the + * legacy path. + */ + async elicitInput(params, options) { + this._assertPushApiInServedEra("elicitation/create"); + switch (params.mode ?? "form") { + case "url": + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); + break; + case "form": + if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); + break; + } + return this._sendElicitationLeg(params, options); + } + /** + * The capability-check-free core of {@linkcode elicitInput}. The shim + * uses it because its gate differs from the public checks: a bare + * `elicitation: {}` counts as form support (the pre-mode rule), and + * accepted content passes through unvalidated for parity with the + * modern client driver (handlers validate via the schema-aware + * `acceptedContent` overload and can re-ask). + */ + async _sendElicitationLeg(params, options, behavior) { + const mode = params.mode ?? "form"; + const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; + switch (mode) { + case "url": { + const urlParams = params; + return this.request({ + method: "elicitation/create", + params: urlParams + }, options); + } + case "form": { + const formParams = params.mode === "form" ? params : { + ...params, + mode: "form" + }; + const result = await this.request({ + method: "elicitation/create", + params: formParams + }, options); + if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { + const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); + if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError) throw error; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); + } + return result; + } + } + } + /** + * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` + * notification for the specified elicitation ID. + * + * The notification (and the `elicitationId` it references) exists only on protocol revision + * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the + * returned callback rejects with a typed local error before anything reaches the transport + * (the method is not part of that revision's wire registry). + * + * @param elicitationId The ID of the elicitation to mark as complete. + * @param options Optional notification options. Useful when the completion notification should be related to a prior request. + * @returns A function that emits the completion notification when awaited. + */ + createElicitationCompletionNotifier(elicitationId, options) { + if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); + return () => this.notification({ + method: "notifications/elicitation/complete", + params: { elicitationId } + }, options); + } + /** + * Requests the list of roots from the client. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, + * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 + * push-style server-to-client request model is replaced by input_required results in the + * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. + */ + async listRoots(params, options) { + this._assertPushApiInServedEra("roots/list"); + return this.request({ + method: "roots/list", + params + }, options); + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ + method: "notifications/message", + params + }); + } + async sendResourceUpdated(params) { + return this.notification({ + method: "notifications/resources/updated", + params + }); + } + async sendResourceListChanged() { + return this.notification({ method: "notifications/resources/list_changed" }); + } + async sendToolListChanged() { + return this.notification({ method: "notifications/tools/list_changed" }); + } + async sendPromptListChanged() { + return this.notification({ method: "notifications/prompts/list_changed" }); + } +}; +/** +* The capability set a server advertises on `server/discover`. Pure — never +* mutates the input; the legacy `initialize` advertisement is untouched. +* +* The serving entries serve `subscriptions/listen` themselves, so the +* `listChanged` and `resources.subscribe` capability bits are advertised +* as-is: a modern-era client uses them to decide which notification types to +* request on its listen filter. +*/ +function discoverAdvertisedCapabilities(capabilities) { + return { ...capabilities }; +} + +//#endregion +//#region src/server/mcp.ts +/** +* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. +* For advanced usage (like sending notifications or setting custom request handlers), use the underlying +* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. +* +* @example +* ```ts source="./mcp.examples.ts#McpServer_basicUsage" +* const server = new McpServer({ +* name: 'my-server', +* version: '1.0.0' +* }); +* ``` +*/ +var mcp_DXXb3Vv3_McpServer = class { + /** + * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. + */ + server; + _registeredResources = {}; + _registeredResourceTemplates = {}; + _registeredTools = {}; + _registeredPrompts = {}; + /** + * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 + * registration-time scan and the pre-dispatch validation step share one + * conversion instead of paying it twice per request under the + * per-request-factory `createMcpHandler` model. + */ + _toolInputSchemaJson = {}; + /** + * The JSON-serialized `inputSchema` of a registered tool, or `undefined` + * when no such tool is registered. Used by the HTTP entry's pre-dispatch + * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema + * `tools/list` would emit, before dispatch reaches the handler). + * + * @internal + */ + toolInputSchemaJson(name) { + const tool = this._registeredTools[name]; + if (tool === void 0 || !tool.enabled) return void 0; + if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; + if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; + try { + const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + return json; + } catch { + return; + } + } + constructor(serverInfo, options) { + this.server = new Server(serverInfo, options); + if (options?.capabilities?.tools) this.setToolRequestHandlers(); + if (options?.capabilities?.resources) this.setResourceRequestHandlers(); + if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); + } + /** + * Attaches to the given transport, starts it, and starts listening for messages. + * + * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" + * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); + * const transport = new StdioServerTransport(); + * await server.connect(transport); + * ``` + */ + async connect(transport) { + return await this.server.connect(transport); + } + /** + * Closes the connection. + */ + async close() { + await this.server.close(); + } + _toolHandlersInitialized = false; + setToolRequestHandlers() { + if (this._toolHandlersInitialized) return; + this.server.assertCanSetRequestHandler("tools/list"); + this.server.assertCanSetRequestHandler("tools/call"); + this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); + this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { + const toolDefinition = { + name, + title: tool.title, + description: tool.description, + inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, + annotations: tool.annotations, + icons: tool.icons, + execution: tool.execution, + _meta: tool._meta + }; + if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); + return toolDefinition; + }) })); + this.server.setRequestHandler("tools/call", async (request, ctx) => { + const tool = this._registeredTools[request.params.name]; + if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); + if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); + try { + const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); + const result = await this.executeToolHandler(tool, args, ctx); + await this.validateToolOutput(tool, result, request.params.name); + if (isInputRequiredResult(result)) return result; + return this.server.projectCallToolResult(result, tool.outputSchemaJson); + } catch (error) { + if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; + return this.createToolError(error instanceof Error ? error.message : String(error)); + } + }); + this._toolHandlersInitialized = true; + } + /** + * Creates a tool error result. + * + * @param errorMessage - The error message. + * @returns The tool error result. + */ + createToolError(errorMessage) { + return { + content: [{ + type: "text", + text: errorMessage + }], + isError: true + }; + } + /** + * Validates tool input arguments against the tool's input schema. + */ + async validateToolInput(tool, args, toolName) { + if (!tool.inputSchema) return; + const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); + return parseResult.data; + } + /** + * Validates tool output against the tool's output schema. + */ + async validateToolOutput(tool, result, toolName) { + if (!tool.outputSchema) return; + if (isInputRequiredResult(result)) return; + if (result.isError) return; + if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); + const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); + } + /** + * Executes a tool handler. + */ + async executeToolHandler(tool, args, ctx) { + return tool.executor(args, ctx); + } + _completionHandlerInitialized = false; + setCompletionRequestHandler() { + if (this._completionHandlerInitialized) return; + this.server.assertCanSetRequestHandler("completion/complete"); + this.server.registerCapabilities({ completions: {} }); + this.server.setRequestHandler("completion/complete", async (request) => { + switch (request.params.ref.type) { + case "ref/prompt": + assertCompleteRequestPrompt(request); + return this.handlePromptCompletion(request, request.params.ref); + case "ref/resource": + assertCompleteRequestResourceTemplate(request); + return this.handleResourceCompletion(request, request.params.ref); + default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); + } + }); + this._completionHandlerInitialized = true; + } + async handlePromptCompletion(request, ref) { + const prompt = this._registeredPrompts[ref.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); + if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; + const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); + if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; + const completer = getCompleter(field); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + async handleResourceCompletion(request, ref) { + const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); + if (!template) { + if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); + } + const completer = template.resourceTemplate.completeCallback(request.params.argument.name); + if (!completer) return EMPTY_COMPLETION_RESULT; + return createCompletionResult(await completer(request.params.argument.value, request.params.context)); + } + _resourceHandlersInitialized = false; + setResourceRequestHandlers() { + if (this._resourceHandlersInitialized) return; + this.server.assertCanSetRequestHandler("resources/list"); + this.server.assertCanSetRequestHandler("resources/templates/list"); + this.server.assertCanSetRequestHandler("resources/read"); + this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); + this.server.setRequestHandler("resources/list", async (_request, ctx) => { + const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ + uri, + name: resource.name, + ...resource.metadata + })); + const templateResources = []; + for (const template of Object.values(this._registeredResourceTemplates)) { + if (!template.resourceTemplate.listCallback) continue; + const result = await template.resourceTemplate.listCallback(ctx); + for (const resource of result.resources) templateResources.push({ + ...template.metadata, + ...resource + }); + } + return { resources: [...resources, ...templateResources] }; + }); + this.server.setRequestHandler("resources/templates/list", async () => { + return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ + name, + uriTemplate: template.resourceTemplate.uriTemplate.toString(), + ...template.metadata + })) }; + }); + this.server.setRequestHandler("resources/read", async (request, ctx) => { + let uri; + try { + uri = new URL(request.params.uri); + } catch { + throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { + uri: request.params.uri, + reason: "invalid_uri" + }); + } + const resource = this._registeredResources[uri.toString()]; + if (resource) { + if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); + return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); + } + for (const template of Object.values(this._registeredResourceTemplates)) { + const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); + if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); + } + throw new ResourceNotFoundError(request.params.uri); + }); + this._resourceHandlersInitialized = true; + } + _promptHandlersInitialized = false; + setPromptRequestHandlers() { + if (this._promptHandlersInitialized) return; + this.server.assertCanSetRequestHandler("prompts/list"); + this.server.assertCanSetRequestHandler("prompts/get"); + this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); + this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { + return { + name, + title: prompt.title, + description: prompt.description, + arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, + icons: prompt.icons, + _meta: prompt._meta + }; + }) })); + this.server.setRequestHandler("prompts/get", async (request, ctx) => { + const prompt = this._registeredPrompts[request.params.name]; + if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); + if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); + return prompt.handler(request.params.arguments, ctx); + }); + this._promptHandlersInitialized = true; + } + registerResource(name, uriOrTemplate, config, readCallback) { + const cacheHint = config.cacheHint; + let metadata = config; + if (cacheHint !== void 0) { + assertValidCacheHint(cacheHint, `resource ${name}`); + const rest = { ...config }; + delete rest.cacheHint; + metadata = rest; + } + if (typeof uriOrTemplate === "string") { + if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); + const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResource; + } else { + if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); + const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); + if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; + this.setResourceRequestHandlers(); + this.sendResourceListChanged(); + return registeredResourceTemplate; + } + } + _createRegisteredResource(name, title, uri, metadata, readCallback) { + const registeredResource = { + name, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResource.update({ enabled: false }), + enable: () => registeredResource.update({ enabled: true }), + remove: () => registeredResource.update({ uri: null }), + update: (updates) => { + if (updates.uri !== void 0 && updates.uri !== uri) { + delete this._registeredResources[uri]; + if (updates.uri) this._registeredResources[updates.uri] = registeredResource; + } + if (updates.name !== void 0) registeredResource.name = updates.name; + if (updates.title !== void 0) registeredResource.title = updates.title; + if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResources[uri] = registeredResource; + return registeredResource; + } + _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { + const registeredResourceTemplate = { + resourceTemplate: template, + title, + metadata, + readCallback, + enabled: true, + disable: () => registeredResourceTemplate.update({ enabled: false }), + enable: () => registeredResourceTemplate.update({ enabled: true }), + remove: () => registeredResourceTemplate.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredResourceTemplates[name]; + if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; + } + if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; + if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; + if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; + if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; + if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; + this.sendResourceListChanged(); + } + }; + this._registeredResourceTemplates[name] = registeredResourceTemplate; + const variableNames = template.uriTemplate.variableNames; + if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); + return registeredResourceTemplate; + } + _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { + let currentArgsSchema = argsSchema; + let currentCallback = callback; + const registeredPrompt = { + title, + description, + argsSchema, + icons, + _meta, + handler: createPromptHandler(name, argsSchema, callback), + enabled: true, + disable: () => registeredPrompt.update({ enabled: false }), + enable: () => registeredPrompt.update({ enabled: true }), + remove: () => registeredPrompt.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + delete this._registeredPrompts[name]; + if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; + } + if (updates.title !== void 0) registeredPrompt.title = updates.title; + if (updates.description !== void 0) registeredPrompt.description = updates.description; + if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; + if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; + let needsHandlerRegen = false; + if (updates.argsSchema !== void 0) { + registeredPrompt.argsSchema = updates.argsSchema; + currentArgsSchema = updates.argsSchema; + needsHandlerRegen = true; + } + if (updates.callback !== void 0) { + currentCallback = updates.callback; + needsHandlerRegen = true; + } + if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); + if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; + this.sendPromptListChanged(); + } + }; + this._registeredPrompts[name] = registeredPrompt; + if (argsSchema) { + const shape = getSchemaShape(argsSchema); + if (shape) { + if (Object.values(shape).some((field) => { + return isCompletable(unwrapOptionalSchema(field)); + })) this.setCompletionRequestHandler(); + } + } + return registeredPrompt; + } + _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { + validateAndWarnToolName(name); + if (inputSchema !== void 0) try { + const json = standardSchemaToJsonSchema(inputSchema, "input"); + this._toolInputSchemaJson[name] = json; + const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); + if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); + } catch {} + let currentHandler = handler; + const registeredTool = { + title, + description, + inputSchema, + outputSchema, + outputSchemaJson: convertOutputSchemaJson(outputSchema), + annotations, + icons, + execution, + _meta, + handler, + executor: createToolExecutor(inputSchema, handler), + enabled: true, + disable: () => registeredTool.update({ enabled: false }), + enable: () => registeredTool.update({ enabled: true }), + remove: () => registeredTool.update({ name: null }), + update: (updates) => { + if (updates.name !== void 0 && updates.name !== name) { + if (typeof updates.name === "string") validateAndWarnToolName(updates.name); + delete this._registeredTools[name]; + delete this._toolInputSchemaJson[name]; + if (updates.name) { + delete this._toolInputSchemaJson[updates.name]; + this._registeredTools[updates.name] = registeredTool; + name = updates.name; + } + } + if (updates.title !== void 0) registeredTool.title = updates.title; + if (updates.description !== void 0) registeredTool.description = updates.description; + let needsExecutorRegen = false; + if (updates.paramsSchema !== void 0) { + registeredTool.inputSchema = updates.paramsSchema; + delete this._toolInputSchemaJson[name]; + needsExecutorRegen = true; + } + if (updates.callback !== void 0) { + registeredTool.handler = updates.callback; + currentHandler = updates.callback; + needsExecutorRegen = true; + } + if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); + if (updates.outputSchema !== void 0) { + registeredTool.outputSchema = updates.outputSchema; + registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); + } + if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; + if (updates.icons !== void 0) registeredTool.icons = updates.icons; + if (updates._meta !== void 0) registeredTool._meta = updates._meta; + if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; + this.sendToolListChanged(); + } + }; + this._registeredTools[name] = registeredTool; + this.setToolRequestHandlers(); + this.sendToolListChanged(); + return registeredTool; + } + registerTool(name, config, cb) { + if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); + const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; + return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); + } + registerPrompt(name, config, cb) { + if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); + const { title, description, argsSchema, icons, _meta } = config; + const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); + this.setPromptRequestHandlers(); + this.sendPromptListChanged(); + return registeredPrompt; + } + /** + * Checks if the server is connected to a transport. + * @returns `true` if the server is connected + */ + isConnected() { + return this.server.transport !== void 0; + } + /** + * Sends a logging message to the client, if connected. + * Note: You only need to send the parameters object, not the entire JSON-RPC message. + * @see {@linkcode LoggingMessageNotification} + * @param params + * @param sessionId Optional for stateless transports and backward compatibility. + * + * @example + * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" + * await server.sendLoggingMessage({ + * level: 'info', + * data: 'Processing complete' + * }); + * ``` + * + * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). + * Remains functional during the deprecation window (at least twelve months). + * Migrate to stderr logging (STDIO servers) or OpenTelemetry. + */ + async sendLoggingMessage(params, sessionId) { + return this.server.sendLoggingMessage(params, sessionId); + } + /** + * Sends a resource list changed event to the client, if connected. + */ + sendResourceListChanged() { + if (this.isConnected()) this.server.sendResourceListChanged(); + } + /** + * Sends a tool list changed event to the client, if connected. + */ + sendToolListChanged() { + if (this.isConnected()) this.server.sendToolListChanged(); + } + /** + * Sends a prompt list changed event to the client, if connected. + */ + sendPromptListChanged() { + if (this.isConnected()) this.server.sendPromptListChanged(); + } +}; +/** +* A resource template combines a URI pattern with optional functionality to enumerate +* all resources matching that pattern. +*/ +var ResourceTemplate = class { + _uriTemplate; + constructor(uriTemplate, _callbacks) { + this._callbacks = _callbacks; + this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; + } + /** + * Gets the URI template pattern. + */ + get uriTemplate() { + return this._uriTemplate; + } + /** + * Gets the list callback, if one was provided. + */ + get listCallback() { + return this._callbacks.list; + } + /** + * Gets the callback for completing a specific URI template variable, if one was provided. + */ + completeCallback(variable) { + return this._callbacks.complete?.[variable]; + } +}; +/** +* Creates an executor that invokes the handler with the appropriate arguments. +* When `inputSchema` is defined, the handler is called with `(args, ctx)`. +* When `inputSchema` is undefined, the handler is called with just `(ctx)`. +*/ +function createToolExecutor(inputSchema, handler) { + if (inputSchema) { + const callback$1 = handler; + return async (args, ctx) => callback$1(args, ctx); + } + const callback = handler; + return async (_args, ctx) => callback(ctx); +} +const EMPTY_OBJECT_JSON_SCHEMA = { + type: "object", + properties: {} +}; +/** +* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} +* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that +* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion +* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). +*/ +function convertOutputSchemaJson(outputSchema) { + if (outputSchema === void 0) return void 0; + try { + return standardSchemaToJsonSchema(outputSchema, "output"); + } catch { + return; + } +} +/** +* Creates a type-safe prompt handler that captures the schema and callback in a closure. +* This eliminates the need for type assertions at the call site. +*/ +function createPromptHandler(name, argsSchema, callback) { + if (argsSchema) { + const typedCallback = callback; + return async (args, ctx) => { + const parseResult = await validateStandardSchema(argsSchema, args); + if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); + return typedCallback(parseResult.data, ctx); + }; + } else { + const typedCallback = callback; + return async (_args, ctx) => { + return typedCallback(ctx); + }; + } +} +function createCompletionResult(suggestions) { + return { completion: { + values: suggestions.map(String).slice(0, 100), + total: suggestions.length, + hasMore: suggestions.length > 100 + } }; +} +const EMPTY_COMPLETION_RESULT = { completion: { + values: [], + hasMore: false +} }; +/** @internal Gets the shape of a Zod object schema */ +function getSchemaShape(schema) { + const candidate = schema; + if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; +} +/** @internal Checks if a Zod schema is optional */ +function isOptionalSchema(schema) { + return schema?.type === "optional"; +} +/** @internal Unwraps an optional Zod schema */ +function unwrapOptionalSchema(schema) { + if (!isOptionalSchema(schema)) return schema; + return schema.def?.innerType ?? schema; +} + +//#endregion + +//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map + + + + +//#region src/server/perRequestTransport.ts +/** +* The per-request micro-transport: a real, connected `Transport` whose whole +* lifetime is one HTTP exchange. See the module documentation for the +* response shapes it produces. +*/ +var PerRequestHTTPServerTransport = class { + onclose; + onerror; + onmessage; + _classification; + _responseMode; + _started = false; + _used = false; + _closed = false; + _terminalDelivered = false; + /** + * `true` only while the inbound message is being delivered synchronously + * to the connected protocol layer. The pre-handler gates (the era + * registry gate, the edge→instance handoff check, the missing-handler + * rejection) answer inside this window; request handlers always run + * after it (the protocol layer defers them to a microtask). An error + * sent inside the window is therefore ladder-originated, and an error + * sent after it is handler-produced. + */ + _dispatchWindowOpen = false; + _requestId; + _deferredResponse; + _sse; + _abortCleanup; + _keepAliveMs; + constructor(options) { + this._classification = options.classification; + this._responseMode = options.responseMode ?? "auto"; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + async start() { + if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); + this._started = true; + } + /** + * Serves the single exchange: delivers the classified message to the + * connected server instance and resolves with the HTTP response. + * + * Throws when called a second time (the transport is strictly + * single-use), or before a server has been connected to the transport. + * The returned promise rejects with a connection-closed error when the + * transport is closed before a response was produced (for example because + * the client disconnected). + */ + async handleMessage(message, extra) { + if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); + if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); + if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); + this._used = true; + const signal = extra?.request?.signal; + if (signal?.aborted) { + await this.close(); + throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); + } + const messageExtra = { + classification: this._classification, + ...extra?.request !== void 0 && { request: extra.request }, + ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } + }; + if (isJSONRPCRequest(message)) { + this._requestId = message.id; + let resolve; + let reject; + const promise = new Promise((promiseResolve, promiseReject) => { + resolve = promiseResolve; + reject = promiseReject; + }); + this._deferredResponse = { + promise, + resolve, + reject, + settled: false + }; + if (signal !== void 0) { + const onAbort = () => void this.close(); + signal.addEventListener("abort", onAbort, { once: true }); + this._abortCleanup = () => signal.removeEventListener("abort", onAbort); + } + this._dispatchWindowOpen = true; + try { + this.onmessage(message, messageExtra); + } finally { + this._dispatchWindowOpen = false; + } + if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); + return promise; + } + this.onmessage(message, messageExtra); + return new Response(null, { status: 202 }); + } + async send(message, options) { + if (this._closed) return; + const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); + const relatedId = isResponse ? message.id : options?.relatedRequestId; + if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { + if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); + return; + } + if (isResponse) { + if (this._terminalDelivered) return; + this._terminalDelivered = true; + const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; + const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; + if (ladderStatus !== void 0 && this._sse === void 0) { + this.settleResponse(Response.json(message, { + status: ladderStatus, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._sse !== void 0 || this._responseMode === "sse") { + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + this.finalizeStream(); + return; + } + this.settleResponse(Response.json(message, { + status: 200, + headers: { "Content-Type": "application/json" } + })); + queueMicrotask(() => void this.close()); + return; + } + if (this._responseMode === "json") return; + if (this._sse === void 0) this.upgradeToSse(); + this.writeMessageFrame(message); + } + /** + * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the + * exchange is not currently streaming. + */ + writeCommentFrame(comment) { + if (this._closed || this._sse === void 0 || this._sse.closed) return; + const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); + this.writeFrame(`${frame}\n\n`); + } + async close() { + if (this._closed) return; + this._closed = true; + this._abortCleanup?.(); + this._abortCleanup = void 0; + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { + this._deferredResponse.settled = true; + this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); + } + this.onclose?.(); + } + settleResponse(response) { + if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; + this._deferredResponse.settled = true; + this._deferredResponse.resolve(response); + } + upgradeToSse() { + let controller; + const readable = new ReadableStream({ + start: (streamController) => { + controller = streamController; + }, + cancel: () => { + this.close(); + } + }); + this._sse = { + controller, + encoder: new TextEncoder(), + closed: false + }; + this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); + this.settleResponse(new Response(readable, { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + } + })); + } + finalizeStream() { + if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); + if (this._sse !== void 0 && !this._sse.closed) { + this._sse.closed = true; + try { + this._sse.controller.close(); + } catch {} + } + queueMicrotask(() => void this.close()); + } + writeMessageFrame(message) { + this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); + } + writeFrame(frame) { + if (this._sse === void 0 || this._sse.closed) return; + try { + this._sse.controller.enqueue(this._sse.encoder.encode(frame)); + } catch (error) { + this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); + } + } +}; + +//#endregion +//#region src/server/invoke.ts +/** +* Serves one classified inbound message on the given server instance and +* returns the HTTP response for the exchange. +* +* The instance is connected to a fresh single-exchange transport, the message +* is injected through the normal transport message path, and whatever the +* dispatch layer produces (the handler result, a protocol-level rejection, or +* streamed related messages followed by the result) is captured as the +* returned `Response`. For request exchanges, teardown rides the transport's +* close chain once the terminal response has been delivered; notification +* exchanges resolve with the 202 response immediately and do NOT run the +* close chain — the transport stays connected until the caller closes it or +* drops the per-request instance, which is the caller's choice either way. +*/ +async function invoke(server, message, ctx) { + const transport = new PerRequestHTTPServerTransport({ + classification: ctx.classification, + ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, + ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } + }); + await server.connect(transport); + return transport.handleMessage(message, { + ...ctx.request !== void 0 && { request: ctx.request }, + ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } + }); +} + +//#endregion +//#region src/server/streamableHttp.ts +/** +* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification +* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). +* +* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. +* +* In stateful mode: +* - Session ID is generated and included in response headers +* - Session ID is always included in initialization responses +* - Requests with invalid session IDs are rejected with `404 Not Found` +* - Non-initialization requests without a session ID are rejected with `400 Bad Request` +* - State is maintained in-memory (connections, message history) +* +* In stateless mode: +* - No Session ID is included in any responses +* - No session validation is performed +* +* @example Stateful setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: () => crypto.randomUUID() +* }); +* +* await server.connect(transport); +* ``` +* +* @example Stateless setup +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" +* const transport = new WebStandardStreamableHTTPServerTransport({ +* sessionIdGenerator: undefined +* }); +* ``` +* +* @example Hono.js +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" +* app.all('/mcp', async c => { +* return transport.handleRequest(c.req.raw); +* }); +* ``` +* +* @example Cloudflare Workers +* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" +* const worker = { +* async fetch(request: Request): Promise { +* return transport.handleRequest(request); +* } +* }; +* ``` +*/ +var WebStandardStreamableHTTPServerTransport = class { + sessionIdGenerator; + _started = false; + _closed = false; + _streamMapping = /* @__PURE__ */ new Map(); + _requestToStreamMapping = /* @__PURE__ */ new Map(); + _requestResponseMap = /* @__PURE__ */ new Map(); + _initialized = false; + _enableJsonResponse = false; + _standaloneSseStreamId = "_GET_stream"; + _eventStore; + _onsessioninitialized; + _onsessionclosed; + _allowedHosts; + _allowedOrigins; + _enableDnsRebindingProtection; + _retryInterval; + _supportedProtocolVersions; + _keepAliveMs; + sessionId; + onclose; + onerror; + onmessage; + constructor(options = {}) { + this.sessionIdGenerator = options.sessionIdGenerator; + this._enableJsonResponse = options.enableJsonResponse ?? false; + this._eventStore = options.eventStore; + this._onsessioninitialized = options.onsessioninitialized; + this._onsessionclosed = options.onsessionclosed; + this._allowedHosts = options.allowedHosts; + this._allowedOrigins = options.allowedOrigins; + this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; + this._retryInterval = options.retryInterval; + this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; + this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; + } + startKeepAlive(controller, encoder) { + if (this._closed) return void 0; + const timer = armSseKeepAlive(this._keepAliveMs, () => { + try { + controller.enqueue(encoder.encode(": keepalive\n\n")); + } catch { + if (timer !== void 0) clearInterval(timer); + } + }); + return timer; + } + /** + * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op + * for the Streamable HTTP transport as connections are managed per-request. + */ + async start() { + if (this._started) throw new Error("Transport already started"); + this._started = true; + } + /** + * Sets the supported protocol versions for header validation. + * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. + */ + setSupportedProtocolVersions(versions) { + this._supportedProtocolVersions = versions; + } + /** + * Helper to create a JSON error response + */ + createJsonErrorResponse(status, code, message, options) { + const error = { + code, + message + }; + if (options?.data !== void 0) error.data = options.data; + return Response.json({ + jsonrpc: "2.0", + error, + id: null + }, { + status, + headers: { + "Content-Type": "application/json", + ...options?.headers + } + }); + } + /** + * Validates request headers for DNS rebinding protection. + * @returns Error response if validation fails, `undefined` if validation passes. + */ + validateRequestHeaders(req) { + if (!this._enableDnsRebindingProtection) return; + if (this._allowedHosts && this._allowedHosts.length > 0) { + const hostHeader = req.headers.get("host"); + if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { + const error = `Invalid Host header: ${hostHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + if (this._allowedOrigins && this._allowedOrigins.length > 0) { + const originHeader = req.headers.get("origin"); + if (originHeader && !this._allowedOrigins.includes(originHeader)) { + const error = `Invalid Origin header: ${originHeader}`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(403, -32e3, error); + } + } + } + /** + * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` + * Returns a `Response` object (Web Standard) + */ + async handleRequest(req, options) { + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const validationError = this.validateRequestHeaders(req); + if (validationError) return validationError; + switch (req.method) { + case "POST": return this.handlePostRequest(req, options); + case "GET": return this.handleGetRequest(req); + case "DELETE": return this.handleDeleteRequest(req); + default: return this.handleUnsupportedRequest(); + } + } + /** + * Returns true if the client's protocol version supports empty SSE data in + * priming events (the fix shipped with protocol version `2025-11-25`). + * + * The version is checked for membership in this transport instance's + * supported protocol versions rather than with an open-ended + * `>= '2025-11-25'` comparison: the value may come from an `initialize` + * request body, which (unlike the `MCP-Protocol-Version` header) is not + * validated against `supportedProtocolVersions` before reaching this + * check. An unknown future version string must not silently enable + * behavior reserved for versions this transport actually supports. + */ + supportsEmptySSEData(protocolVersion) { + return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; + } + /** + * Writes a priming event to establish resumption capability. + * Only sends if `eventStore` is configured (opt-in for resumability) and + * the client's protocol version supports empty SSE data (a supported + * version that is >= `2025-11-25`). + */ + async writePrimingEvent(controller, encoder, streamId, protocolVersion) { + if (!this._eventStore) return; + if (!this.supportsEmptySSEData(protocolVersion)) return; + const primingEventId = await this._eventStore.storeEvent(streamId, {}); + let primingEvent = `id: ${primingEventId}\ndata: \n\n`; + if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; + controller.enqueue(encoder.encode(primingEvent)); + } + /** + * Handles `GET` requests for SSE stream + */ + async handleGetRequest(req) { + if (!req.headers.get("accept")?.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); + } + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + if (this._eventStore) { + const lastEventId = req.headers.get("last-event-id"); + if (lastEventId) return this.replayEvents(lastEventId); + } + if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); + } + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + this._streamMapping.set(this._standaloneSseStreamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(this._standaloneSseStreamId); + try { + streamController.close(); + } catch {} + } + }); + keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } + /** + * Replays events that would have been sent after the specified event ID + * Only used when resumability is enabled + */ + async replayEvents(lastEventId) { + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); + return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); + } + try { + let streamId; + if (this._eventStore.getStreamIdForEventId) { + streamId = await this._eventStore.getStreamIdForEventId(lastEventId); + if (!streamId) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); + return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); + } + if (this._streamMapping.get(streamId) !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); + return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); + } + } + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + let cancelled = false; + let replayedStreamId; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + cancelled = true; + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); + } + }); + const replayedEventIds = /* @__PURE__ */ new Set(); + replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { + replayedEventIds.add(eventId); + if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { + streamController.close(); + } catch {} + } }); + if (this._closed || cancelled) { + try { + streamController.close(); + } catch {} + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + this._streamMapping.get(replayedStreamId)?.cleanup(); + this._streamMapping.set(replayedStreamId, { + controller: streamController, + encoder, + replayedEventIds, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + }); + if (replayedStreamId !== this._standaloneSseStreamId) { + if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { + this._streamMapping.delete(replayedStreamId); + try { + streamController.close(); + } catch {} + } + } + if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { headers }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); + } + } + /** + * Writes an event to an SSE stream via controller with proper formatting + */ + writeSSEEvent(controller, encoder, message, eventId) { + try { + let eventData = `event: message\n`; + if (eventId) eventData += `id: ${eventId}\n`; + eventData += `data: ${JSON.stringify(message)}\n\n`; + controller.enqueue(encoder.encode(eventData)); + return true; + } catch (error) { + this.onerror?.(error); + return false; + } + } + /** + * Handles unsupported requests (`PUT`, `PATCH`, etc.) + */ + handleUnsupportedRequest() { + this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: "Method not allowed." + }, + id: null + }, { + status: 405, + headers: { + Allow: "GET, POST, DELETE", + "Content-Type": "application/json" + } + }); + } + /** + * Handles `POST` requests containing JSON-RPC messages + */ + async handlePostRequest(req, options) { + try { + const acceptHeader = req.headers.get("accept"); + if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { + this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); + return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); + } + if (!isJsonContentType(req.headers.get("content-type"))) { + this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const request = req; + let rawMessage; + if (options?.parsedBody === void 0) try { + rawMessage = await req.json(); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); + } + else rawMessage = options.parsedBody; + let messages; + try { + messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); + if (isInitializationRequest) { + if (this._initialized && this.sessionId !== void 0) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); + } + if (messages.length > 1) { + this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); + return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); + } + this.sessionId = this.sessionIdGenerator?.(); + this._initialized = true; + if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); + } + if (!isInitializationRequest) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + } + if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); + if (!messages.some((element) => isJSONRPCRequest(element))) { + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + return new Response(null, { status: 202 }); + } + const streamId = crypto.randomUUID(); + const initRequest = messages.find((m) => isInitializeRequest(m)); + const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; + if (this._enableJsonResponse) return new Promise((resolve) => { + this._streamMapping.set(streamId, { + resolveJson: resolve, + cleanup: () => { + this._streamMapping.delete(streamId); + } + }); + for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); + for (const message of messages) this.onmessage?.(message, { + authInfo: options?.authInfo, + request + }); + }); + const encoder = new TextEncoder(); + let streamController; + let keepAliveTimer; + const readable = new ReadableStream({ + start: (controller) => { + streamController = controller; + }, + cancel: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); + } + }); + const headers = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache, no-transform", + Connection: "keep-alive", + "X-Accel-Buffering": "no" + }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + for (const message of messages) if (isJSONRPCRequest(message)) { + this._streamMapping.set(streamId, { + controller: streamController, + encoder, + cleanup: () => { + if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); + this._streamMapping.delete(streamId); + try { + streamController.close(); + } catch {} + } + }); + this._requestToStreamMapping.set(message.id, streamId); + } + await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); + for (const message of messages) { + let closeSSEStream; + let closeStandaloneSSEStream; + if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { + closeSSEStream = () => { + this.closeSSEStream(message.id); + }; + closeStandaloneSSEStream = () => { + this.closeStandaloneSSEStream(); + }; + } + this.onmessage?.(message, { + authInfo: options?.authInfo, + request, + closeSSEStream, + closeStandaloneSSEStream + }); + } + if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); + return new Response(readable, { + status: 200, + headers + }); + } catch (error) { + this.onerror?.(error); + return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); + } + } + /** + * Handles `DELETE` requests to terminate sessions + */ + async handleDeleteRequest(req) { + const sessionError = this.validateSession(req); + if (sessionError) return sessionError; + const protocolError = this.validateProtocolVersion(req); + if (protocolError) return protocolError; + try { + await Promise.resolve(this._onsessionclosed?.(this.sessionId)); + return new Response(null, { status: 200 }); + } finally { + await this.close(); + } + } + /** + * Validates session ID for non-initialization requests. + * Returns `Response` error if invalid, `undefined` otherwise + */ + validateSession(req) { + if (this.sessionIdGenerator === void 0) return; + if (!this._initialized) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); + } + const sessionId = req.headers.get("mcp-session-id"); + if (!sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); + return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); + } + if (sessionId !== this.sessionId) { + this.onerror?.(/* @__PURE__ */ new Error("Session not found")); + return this.createJsonErrorResponse(404, -32001, "Session not found"); + } + } + /** + * Validates the `MCP-Protocol-Version` header on incoming requests. + * + * For initialization: Version negotiation handles unknown versions gracefully + * (server responds with its supported version). + * + * For subsequent requests with `MCP-Protocol-Version` header: + * - Accept if in supported list + * - 400 if unsupported + * + * For HTTP requests without the `MCP-Protocol-Version` header: + * - Accept and default to the version negotiated at initialization + */ + validateProtocolVersion(req) { + const protocolVersion = req.headers.get("mcp-protocol-version"); + if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { + const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; + this.onerror?.(new Error(error)); + return this.createJsonErrorResponse(400, -32e3, error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + for (const { cleanup } of this._streamMapping.values()) cleanup(); + this._streamMapping.clear(); + this._requestResponseMap.clear(); + this.onclose?.(); + } + /** + * Close an SSE stream for a specific request, triggering client reconnection. + * Use this to implement polling behavior during long-running operations - + * client will reconnect after the retry interval specified in the priming event. + */ + closeSSEStream(requestId) { + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) return; + const stream = this._streamMapping.get(streamId); + if (stream) stream.cleanup(); + } + /** + * Close the standalone `GET` SSE stream, triggering client reconnection. + * Use this to implement polling behavior for server-initiated notifications. + */ + closeStandaloneSSEStream() { + const stream = this._streamMapping.get(this._standaloneSseStreamId); + if (stream) stream.cleanup(); + } + async send(message, options) { + let requestId = options?.relatedRequestId; + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; + if (requestId === void 0) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); + let eventId; + if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); + const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); + if (standaloneSse === void 0) return; + if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); + return; + } + const streamId = this._requestToStreamMapping.get(requestId); + if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); + let stream = this._streamMapping.get(streamId); + if (!this._enableJsonResponse) { + let eventId; + if (this._eventStore) { + eventId = await this._eventStore.storeEvent(streamId, message); + stream = this._streamMapping.get(streamId); + } + if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); + } + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + this._requestResponseMap.set(requestId, message); + const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); + if (relatedIds.every((id) => this._requestResponseMap.has(id))) { + if (!stream) { + if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); + if (!this._eventStore) { + this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + return; + } + if (this._enableJsonResponse && stream.resolveJson) { + const headers = { "Content-Type": "application/json" }; + if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; + const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); + if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { + status: 200, + headers + })); + else stream.resolveJson(Response.json(responses, { + status: 200, + headers + })); + stream.cleanup(); + } else stream.cleanup(); + for (const id of relatedIds) { + this._requestResponseMap.delete(id); + this._requestToStreamMapping.delete(id); + } + } + } + } +}; + +//#endregion +//#region src/server/createMcpHandler.ts +/** +* The JSON-RPC id to echo on an entry-built error response: the body's `id` +* when the body is a single JSON-RPC request whose id is a string or number, +* `null` otherwise. Error responses must carry the id of the request they +* correspond to whenever it could be read; `null` is reserved for the cases +* where no single request id is determinable — unparseable bodies, body-less +* methods, notifications, posted responses and batch arrays. +*/ +function echoableRequestId(body) { + if (body === null || typeof body !== "object" || Array.isArray(body)) return null; + const { method, id } = body; + if (typeof method !== "string") return null; + return typeof id === "string" || typeof id === "number" ? id : null; +} +function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { + return Response.json({ + jsonrpc: "2.0", + error: { + code, + message, + ...data !== void 0 && { data } + }, + id + }, { status: httpStatus }); +} +function rejectionResponse(rejection, id = null) { + return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); +} +function toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} +function internalServerErrorResponse(id = null) { + return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); +} +/** +* The entry's default legacy serving (`legacy: 'stateless'`): per-request +* stateless serving of 2025-era traffic using the same factory as the modern +* path. Exported as a standalone building block for hand-wired compositions +* (for example mounting legacy stateless serving on its own route next to a +* strict modern endpoint). +* +* Each POST is served by a fresh instance from the factory connected to a +* fresh streamable HTTP transport constructed with only +* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. +* Because serving is per-request and stateless, GET and DELETE (2025 session +* operations) are answered with `405` / `Method not allowed.`, exactly like the +* canonical stateless example. +* +* The optional `onerror` callback receives factory and serving failures on +* this leg (reporting only — the response stays the 500 internal-error body). +* The entry passes its own `onerror` here when expanding the default, so +* legacy-leg failures are never silently swallowed. +*/ +function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { + return async (request, options) => { + if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); + try { + const product = await factory({ + era: "legacy", + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + requestInfo: request + }); + const transport = new WebStandardStreamableHTTPServerTransport({ + sessionIdGenerator: void 0, + ...keepAliveMs !== void 0 && { keepAliveMs } + }); + await product.connect(transport); + const teardown = () => { + transport.close().catch(() => {}); + product.close().catch(() => {}); + }; + request.signal?.addEventListener("abort", teardown, { once: true }); + const response = await transport.handleRequest(request, { + ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, + ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } + }); + if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { + teardown(); + return response; + } + const reader = response.body.getReader(); + let toreDown = false; + const completeExchange = () => { + if (!toreDown) { + toreDown = true; + teardown(); + } + }; + const monitoredBody = new ReadableStream({ + pull: async (controller) => { + try { + const { done, value } = await reader.read(); + if (done) { + completeExchange(); + controller.close(); + return; + } + if (value !== void 0) controller.enqueue(value); + } catch (error) { + completeExchange(); + controller.error(error); + } + }, + cancel: (reason) => { + completeExchange(); + return reader.cancel(reason).catch(() => {}); + } + }); + return new Response(monitoredBody, { + status: response.status, + statusText: response.statusText, + headers: response.headers + }); + } catch (error) { + try { + onerror?.(toError(error)); + } catch {} + return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); + } + }; +} +function legacyStatelessFallback(factory, onerror) { + return createLegacyStatelessFallback(factory, onerror); +} +/** +* The entry's classification step: read the request body exactly once (unless +* a pre-parsed body is supplied) and classify the request with +* {@linkcode classifyInboundRequest}. This is the single code path behind both +* {@linkcode createMcpHandler}'s routing and the exported +* {@linkcode isLegacyRequest} predicate, so the two can never disagree. +* +* Pass `needsForward: false` when the caller never reads `forwardRequest` — +* the body-preserving clone is then skipped and `forwardRequest` is the +* (consumed) input request. +*/ +async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { + const httpMethod = request.method.toUpperCase(); + let body; + let parsedBody = providedParsedBody; + let forwardRequest = request; + let unparseable = false; + if (httpMethod === "POST") { + if (parsedBody === void 0) { + if (needsForward) forwardRequest = request.clone(); + let bodyText; + try { + bodyText = await request.text(); + } catch { + return { step: "unreadable-body" }; + } + try { + body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); + } catch { + unparseable = true; + } + if (!unparseable && body !== void 0) parsedBody = body; + } else body = parsedBody; + if (unparseable || body === void 0) return { + step: "no-json-body", + forwardRequest + }; + } + return { + step: "classified", + outcome: classifyInboundRequest({ + httpMethod, + protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0, + ...body !== void 0 && { body } + }), + body, + parsedBody, + forwardRequest + }; +} +/** +* Whether {@linkcode createMcpHandler} would route this request to its legacy +* (2025-era) serving rather than the modern (2026-07-28) path. +* +* Call it with just the request: `await isLegacyRequest(request)`. For a +* `POST` the body is read from an internal clone, so the request you pass +* stays fully readable for whichever handler you route it to — no second +* argument is needed. (In a Node `(req, res)` handler, build that `Request` +* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body +* parser, which has already drained the Node stream, build it as +* `toWebRequest(req, req.body)` so the bytes come from the parsed body — +* either way the predicate still takes just the request.) The optional +* `parsedBody` is a perf escape hatch for a body you already hold parsed: +* pass it and the predicate classifies from the value directly, reading and +* cloning nothing. It is needed, not just faster, when the request's own +* body was already read — the internal clone is then impossible (cloning a +* used body throws a `TypeError`), so such a single-argument call rejects +* instead of guessing. +* +* This is the entry's own classification step exported as a predicate — it +* runs exactly the code `createMcpHandler` runs to make the routing decision, +* not a re-implementation — so a hand-wired composition that branches on it +* can never disagree with the entry. It is classification only: hand-wired +* compositions must validate Content-Type themselves (415 for POSTs whose +* media type is not `application/json`, via {@linkcode isJsonContentType}) +* before dispatching either leg — routing the legacy leg into the SDK +* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy +* deployment (for example a sessionful streamable HTTP wiring) serving 2025 +* traffic next to a strict modern endpoint, now that the entry has no +* handler-valued `legacy` option: +* +* ```ts +* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; +* +* const modern = createMcpHandler(factory, { legacy: 'reject' }); +* +* export default { +* async fetch(request: Request): Promise { +* if (await isLegacyRequest(request)) { +* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring +* return myExistingLegacyHandler(request); +* } +* return modern.fetch(request); +* } +* }; +* ``` +* +* Semantics (identical to the entry's routing): +* +* - Returns `true` only for requests with no per-request `_meta` envelope +* claim: claim-less POSTs (including the `initialize` handshake and 2025-era +* notification POSTs without a modern protocol-version header), body-less +* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted +* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. +* - Returns `false` for everything the modern path answers, including its +* validation-ladder rejections: a request carrying the envelope claim (even +* one naming a revision the endpoint does not serve — the modern path +* answers it with the unsupported-protocol-version error), a malformed +* envelope behind a present claim (answered `-32602`), a request whose +* `MCP-Protocol-Version` header names a modern revision but that lacks the +* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers +* routing on the predicate must send `false` traffic to the modern handler, +* never to a legacy handler — the modern path owns those error answers. +* - `server/discover` probes sent by negotiating clients always carry the +* envelope claim, so they are never legacy; a hand-built claim-less POST to +* a method named `server/discover` has no claim and classifies legacy, +* exactly as the entry itself routes it. +*/ +async function isLegacyRequest(request, parsedBody) { + const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); + return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; +} +/** +* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a +* per-request server factory and, by default, falls back to old-school +* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a +* modern-only strict endpoint. +* +* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, +* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap +* the handler once with `toNodeHandler(handler)` from +* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, +* put Origin/Host validation in front of the handler — the entry itself is +* deliberately validation-free: +* +* ```ts +* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; +* +* export default { +* async fetch(request: Request): Promise { +* const rejected = +* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? +* originValidationResponse(request, localhostAllowedOrigins()); +* return rejected ?? handler.fetch(request); +* } +* }; +* ``` +* +* Use ONE factory for both legs: the same tools/resources/prompts definition +* backs the modern path and the stateless legacy fallback, so the two eras can +* never drift apart. To keep an existing legacy deployment (for example a +* sessionful streamable HTTP wiring) serving 2025 traffic instead of the +* stateless fallback, route in user land with {@linkcode isLegacyRequest} in +* front of a strict handler — see that predicate's documentation for the +* pattern. Power users composing transport-neutral routing can also use the +* exported building blocks directly: {@linkcode classifyInboundRequest} for +* the era decision and `PerRequestHTTPServerTransport` for single-exchange +* serving — such compositions must reject POSTs whose Content-Type media type +* is not `application/json` (415) before parsing the body, using +* {@linkcode isJsonContentType}; neither building block performs this +* validation itself. +* +* The entry performs no token verification: `authInfo` given to `fetch` is +* passed through to handlers and the factory as-is and is never derived from +* request headers. +*/ +function createMcpHandler(factory, options = {}) { + const { legacy, onerror, responseMode } = options; + if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); + /** Modern per-request instances with an exchange still in flight (close() tears these down). */ + const inflight = /* @__PURE__ */ new Set(); + let closed = false; + const reportError = (error) => { + try { + onerror?.(error); + } catch {} + }; + const bus = options.bus ?? new InMemoryServerEventBus(reportError); + const notify = createServerNotifier(bus); + const listenRouter = createListenRouter({ + bus, + maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, + keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, + onerror: reportError + }); + if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); + const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); + async function serveModern(route, request, authInfo) { + const claimedRevision = route.classification.revision; + if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedRevision ?? "unknown" + }); + reportError(error); + return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); + } + const stdHeaderRejection = validateStandardRequestHeaders({ + httpMethod: request.method, + mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, + mcpNameHeader: request.headers.get("mcp-name") ?? void 0 + }, route); + if (stdHeaderRejection !== void 0) { + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); + return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); + } + const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; + const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; + if (route.messageKind === "request") { + const required = requiredClientCapabilitiesForRequest(route.message.method); + if (required !== void 0) { + const missing = missingClientCapabilities(required, declaredClientCapabilities); + if (missing !== void 0) { + const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); + reportError(error); + return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); + } + } + } + const product = await factory({ + era: "modern", + ...authInfo !== void 0 && { authInfo }, + requestInfo: request + }); + const server = product instanceof McpServer ? product.server : product; + if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { + const capabilities = server.getCapabilities(); + const serverInfo = serverIdentityOf(server); + product.close().catch(reportError); + return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); + } + if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { + const callParams = route.message.params; + const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; + const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); + if (inputSchema !== void 0) { + const scan = scanXMcpHeaderDeclarations(inputSchema); + if (scan.valid && scan.declarations.length > 0) { + const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); + if (rejection !== void 0) { + product.close().catch(reportError); + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); + return rejectionResponse(rejection, route.message.id); + } + } + } + } + setNegotiatedProtocolVersion(server, claimedRevision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (meta !== void 0) seedClientIdentityFromEnvelope(server, { + clientInfo: meta[CLIENT_INFO_META_KEY], + clientCapabilities: declaredClientCapabilities + }); + const previousOnClose = server.onclose; + inflight.add(server); + server.onclose = () => { + inflight.delete(server); + previousOnClose?.(); + }; + try { + const response = await invoke(product, route.message, { + classification: route.classification, + request, + ...authInfo !== void 0 && { authInfo }, + ...responseMode !== void 0 && { responseMode }, + ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } + }); + if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); + return response; + } catch (error) { + if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); + await server.close().catch(() => {}); + inflight.delete(server); + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(route.message)); + } + } + async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { + if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { + ...authInfo !== void 0 && { authInfo }, + ...parsedBody !== void 0 && { parsedBody } + }); + const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (strict === void 0) return new Response(null, { status: 202 }); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); + return rejectionResponse(strict, echoableRequestId(parsedBody)); + } + async function handle(request, requestOptions) { + const authInfo = requestOptions?.authInfo; + if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { + reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); + return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); + } + const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); + if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); + if (classified.step === "no-json-body") { + if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); + return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); + } + const { outcome, body, parsedBody, forwardRequest } = classified; + try { + switch (outcome.kind) { + case "reject": + reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); + return rejectionResponse(outcome, echoableRequestId(body)); + case "modern": return await serveModern(outcome, request, authInfo); + case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); + } + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(body)); + } + } + const fetchFace = async (request, requestOptions) => { + if (closed) throw new Error("This MCP handler has been closed"); + try { + return await handle(request, requestOptions); + } catch (error) { + reportError(toError(error)); + return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); + } + }; + return { + fetch: fetchFace, + notify, + bus, + close: async () => { + closed = true; + listenRouter.closeAll(); + const closing = [...inflight].map((server) => server.close().catch(() => {})); + inflight.clear(); + await Promise.all(closing); + } + }; +} + +//#endregion +//#region src/server/middleware/bearerAuth.ts +function headerQuotedValue(value) { + return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); +} +function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { + let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; + if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; + if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; + return header; +} +/** +* Validate a raw `Authorization` header value as a Bearer token and return +* the verified {@link AuthInfo}. +* +* The runtime-neutral core of Bearer authentication: it parses the header, +* runs the verifier, enforces `requiredScopes`, and rejects tokens without an +* expiration or past it. On any failure it throws an {@link OAuthError} — +* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP +* answer, or use {@link requireBearerAuth} to get both steps as one call. +* +* Framework adapters build on this: `requireBearerAuth` from +* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. +*/ +async function verifyBearerToken(authorizationHeader, options) { + const { verifier, requiredScopes = [] } = options; + if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); + const [type, token] = authorizationHeader.split(" "); + if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); + const authInfo = await verifier.verifyAccessToken(token); + if (requiredScopes.length > 0) { + if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); + } + if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); + else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); + return authInfo; +} +/** +* Build the HTTP answer for a Bearer authentication failure. +* +* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and +* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` +* challenge, with `resource_metadata` when configured so clients can discover +* the Authorization Server), `500` for `server_error`, `400` for anything +* else. A non-`OAuthError` value answers `500 server_error`. The body is the +* OAuth error JSON. +*/ +function bearerAuthChallengeResponse(error, options) { + const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; + if (!(error instanceof OAuthError)) { + const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); + return Response.json(serverError.toResponseObject(), { status: 500 }); + } + switch (error.code) { + case OAuthErrorCode.InvalidToken: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 401, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.InsufficientScope: { + const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); + return Response.json(error.toResponseObject(), { + status: 403, + headers: { "WWW-Authenticate": challenge } + }); + } + case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); + default: return Response.json(error.toResponseObject(), { status: 400 }); + } +} +/** +* Require a valid Bearer token on web-standard requests. +* +* The framework-free counterpart of `requireBearerAuth` from +* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a +* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The +* returned gate resolves to the verified {@link AuthInfo}, or to the +* ready-to-return challenge `Response` when the request must be refused. +* +* @example +* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" +* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); +* +* async function fetchHandler(request: Request): Promise { +* const auth: AuthInfo | Response = await gate(request); +* if (auth instanceof Response) return auth; +* return handler.fetch(request, { authInfo: auth }); +* } +* ``` +*/ +function requireBearerAuth(options) { + const { verifier, requiredScopes = [], resourceMetadataUrl } = options; + const resolved = { + verifier, + requiredScopes, + resourceMetadataUrl + }; + return async (request) => { + const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); + try { + return await verifyBearerToken(authorizationHeader || void 0, resolved); + } catch (error) { + return bearerAuthChallengeResponse(error, resolved); + } + }; +} + +//#endregion +//#region src/server/middleware/hostHeaderValidation.ts +/** +* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). +* +* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). +* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). +*/ +function validateHostHeader(hostHeader, allowedHostnames) { + if (!hostHeader) return { + ok: false, + errorCode: "missing_host", + message: "Missing Host header" + }; + let hostname; + try { + hostname = new URL(`http://${hostHeader}`).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_host_header", + message: `Invalid Host header: ${hostHeader}`, + hostHeader + }; + } + if (!allowedHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_host", + message: `Invalid Host: ${hostname}`, + hostHeader, + hostname + }; + return { + ok: true, + hostname + }; +} +/** +* Convenience allowlist for `localhost` DNS rebinding protection. +*/ +function localhostAllowedHostnames() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for DNS rebinding protection. +* @example +* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" +* const result = validateHostHeader(req.headers.get('host'), ['localhost']); +* ``` +*/ +function hostHeaderValidationResponse(req, allowedHostnames) { + const result = validateHostHeader(req.headers.get("host"), allowedHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/middleware/oauthMetadata.ts +function checkIssuerUrl(issuer, allowInsecure) { + if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); + if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); + if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); +} +/** +* Derive the RFC 9728 Protected Resource Metadata document from +* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL +* (HTTPS required outside localhost) in the process. +* +* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build +* on this; use it directly when serving the document through your own +* routing — or call it once at startup to fail fast on a misconfigured +* issuer before any request arrives. +*/ +function buildOAuthProtectedResourceMetadata(options) { + checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); + return { + resource: options.resourceServerUrl.href, + authorization_servers: [options.oauthMetadata.issuer], + scopes_supported: options.scopesSupported, + resource_name: options.resourceName, + resource_documentation: options.serviceDocumentationUrl?.href + }; +} +/** +* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server +* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. +* +* @example +* ```ts +* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) +* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' +* ``` +*/ +function getOAuthProtectedResourceMetadataUrl(serverUrl) { + return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; +} +/** The RFC 9728 path-aware well-known path for a resource URL. */ +function protectedResourceMetadataPath(resourceServerUrl) { + const rsPath = stripTrailingSlash(resourceServerUrl.pathname); + return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; +} +function stripTrailingSlash(path) { + return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; +} +const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; +function metadataDocumentResponse(request, metadata) { + if (request.method === "OPTIONS") { + const requestedHeaders = request.headers.get("access-control-request-headers"); + return new Response(null, { + status: 204, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": ALLOWED_METHODS, + ...requestedHeaders === null ? {} : { + "Access-Control-Allow-Headers": requestedHeaders, + Vary: "Access-Control-Request-Headers" + } + } + }); + } + if (request.method !== "GET" && request.method !== "HEAD") { + const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); + return Response.json(error.toResponseObject(), { + status: 405, + headers: { + Allow: ALLOWED_METHODS, + "Access-Control-Allow-Origin": "*" + } + }); + } + const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); + return request.method === "HEAD" ? new Response(null, { + status: response.status, + headers: response.headers + }) : response; +} +/** +* Serve the two OAuth discovery documents an MCP server acting as a Resource +* Server exposes, from a web-standard `fetch(request)` handler: +* +* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected +* Resource Metadata, derived from the supplied options (path-aware: the +* resource URL's path is reflected in the route). +* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization +* Server Metadata, passed through verbatim. +* +* Returns the matched document `Response` (JSON with permissive CORS, `405` +* with an `Allow` header for non-GET methods, `204` for CORS preflight), or +* `undefined` when the request path is neither well-known route — fall +* through to your own routing. The framework-free counterpart of +* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with +* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so +* unauthenticated clients can discover the AS from the `401` challenge. +* +* @example +* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" +* async function fetchHandler(request: Request): Promise { +* return oauthMetadataResponse(request, options) ?? serveMcp(request); +* } +* ``` +*/ +function oauthMetadataResponse(request, options) { + const requestPath = stripTrailingSlash(new URL(request.url).pathname); + if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); + if (requestPath === "/.well-known/oauth-authorization-server") { + buildOAuthProtectedResourceMetadata(options); + return metadataDocumentResponse(request, options.oauthMetadata); + } +} + +//#endregion +//#region src/server/middleware/originValidation.ts +/** +* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). +* +* - A missing/empty `Origin` header passes: non-browser clients do not send one, +* and only browser-originated requests carry the header this check defends against. +* - Allowlist items are hostnames only (no scheme, no port), the same convention as +* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). +* - Any present value that cannot be parsed as an origin URL — including the literal +* `null` origin browsers send for opaque contexts — is rejected (deny on failure). +*/ +function validateOriginHeader(originHeader, allowedOriginHostnames) { + if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; + let hostname; + try { + hostname = new URL(originHeader).hostname; + } catch { + return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + } + if (hostname === "") return { + ok: false, + errorCode: "invalid_origin_header", + message: `Invalid Origin header: ${originHeader}`, + originHeader + }; + if (!allowedOriginHostnames.includes(hostname)) return { + ok: false, + errorCode: "invalid_origin", + message: `Invalid Origin: ${hostname}`, + originHeader, + hostname + }; + return { + ok: true, + origin: originHeader, + hostname + }; +} +/** +* Convenience allowlist of localhost-class origin hostnames, mirroring +* `localhostAllowedHostnames`. +*/ +function localhostAllowedOrigins() { + return [ + "localhost", + "127.0.0.1", + "[::1]" + ]; +} +/** +* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC +* error response when the request's `Origin` header is not allowed, and +* `undefined` when the request may proceed. +* +* ```ts +* const rejected = originValidationResponse(request, localhostAllowedOrigins()); +* if (rejected) return rejected; +* ``` +*/ +function originValidationResponse(req, allowedOriginHostnames) { + const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); + if (result.ok) return void 0; + return Response.json({ + jsonrpc: "2.0", + error: { + code: -32e3, + message: result.message + }, + id: null + }, { + status: 403, + headers: { "Content-Type": "application/json" } + }); +} + +//#endregion +//#region src/server/requestStateCodec.ts +const PREFIX = "v1."; +function bytesToBase64Url(bytes) { + let bin = ""; + for (const b of bytes) bin += String.fromCodePoint(b); + return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); +} +function constantTimeTagEqual(a, b) { + if (a.length !== b.length) return false; + let r = 0; + for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); + return r === 0; +} +function base64UrlToBytes(s) { + const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); + const bin = atob(b64); + const bytes = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); + return bytes; +} +/** +* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` +* (protocol revision 2026-07-28). +* +* `requestState` round-trips through the client and is attacker-controlled +* input on re-entry. The SDK applies no protection of its own; this helper is +* the convenience implementation of the spec's integrity MUST so authors don't +* hand-roll HMAC. Wire shape: +* +* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) +* +* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` +* — the binding value is never embedded raw. +* +* The codec is **signed, not encrypted**: the body is integrity-protected but +* the client can base64url-decode it and read the payload (`p`) in clear. Do +* not put secrets in the payload; use an AEAD construction if confidentiality +* is required. The handler reads its payload back via the typed +* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` +* (integrity proven, payload decoded) by the time the handler is entered. +* +* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for +* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). +* See `examples/mrtr/server.ts` for a worked end-to-end example. +* +* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference +* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and +* derives independent cipher / bind-HMAC sub-keys from the operator secret via +* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is +* supplied. This codec deliberately ships only the signed mode and a single +* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and +* an encrypted mode are intentionally out of scope for the initial release. +*/ +function createRequestStateCodec(options) { + const subtle = globalThis.crypto?.subtle; + if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); + const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); + if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); + const ttlSeconds = options.ttlSeconds ?? 600; + if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); + const bind = options.bind; + let cryptoKey; + const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { + name: "HMAC", + hash: "SHA-256" + }, false, ["sign", "verify"]); + const utf8 = new TextEncoder(); + const BIND_LABEL = "mcp.requestState.bind:"; + const bindTag = async (value) => { + return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); + }; + return { + async mint(payload, ctx) { + const envelope = { + p: payload, + exp: Math.floor(Date.now() / 1e3) + ttlSeconds + }; + if (bind !== void 0) { + if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); + envelope.b = await bindTag(bind(ctx)); + } + const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); + return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; + }, + async verify(state, ctx) { + const dot = state.lastIndexOf("."); + if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); + const body = state.slice(3, dot); + let macBytes; + try { + macBytes = base64UrlToBytes(state.slice(dot + 1)); + } catch { + throw new Error("malformed"); + } + if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); + let envelope; + try { + envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); + } catch { + throw new Error("malformed"); + } + if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); + if (bind !== void 0) { + const expected = await bindTag(bind(ctx)); + if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); + } else if (envelope.b !== void 0) throw new Error("bind"); + return envelope.p; + } + }; +} + +//#endregion +//#region src/fromJsonSchema.ts +let _defaultValidator; +function dist_fromJsonSchema(schema, validator) { + return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); +} + +//#endregion + +//# sourceMappingURL=index.mjs.map +const mcpApps = Object.freeze([ + { + "html": "\n\n \n \n \n Service status\n \n \n \n
    \n
    MCP App example
    \n

    No service selected

    \n
    unknown
    \n

    Invoke the readiness tool to inspect a service.

    \n
      \n \n \n \n \n

      \n
      \n \n\n", + "mimeType": "text/html;profile=mcp-app", + "name": "status", + "resourceUri": "ui://mcp-app-example/status.html" + } +]); + +/* export default */ const mcp_status_073c1634_0 = (mcpApps); + +// Generated by agent-bundle. Do not edit. +const meta_name = "mcp-app-example"; +const packageName = "@agent-bundle-example/mcp-app"; +const packageVersion = undefined; +const meta_version = "1.0.0"; +const meta_meta = Object.freeze({ + name: meta_name, + packageName: packageName, + packageVersion: packageVersion, + version: meta_version +}); +/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + + + + +const app = mcp_status_073c1634_0["0"]; +if (app === undefined) throw new Error('Expected the status MCP App.'); +const serviceCatalog = Object.freeze({ + compiler: healthyCompilerStatus, + 'payments-api': Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'P95 latency', + status: 'failing' + }) + ]), + service: 'payments-api', + status: 'degraded', + summary: 'Payment latency is above the release threshold.' + }) +}); +const createStatusServer = ()=>{ + // The compiler stamps this project's identity into `agent-bundle/meta`, so + // the wire identity cannot drift from the config or package.json. + const server = new mcp_DXXb3Vv3_McpServer({ + name: meta_name, + version: (/* inlined export .version */"1.0.0") + }); + server.registerResource(app.name, app.resourceUri, { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + mimeType: app.mimeType + }, async (uri)=>({ + contents: [ + { + mimeType: app.mimeType, + text: app.html, + uri: uri.href + } + ] + })); + server.registerTool('show-status', { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + description: 'Show the health of one example service.', + inputSchema: schemas_object({ + service: schemas_enum([ + 'compiler', + 'payments-api' + ]) + }) + }, async ({ service })=>{ + const result = serviceCatalog[service]; + return { + _meta: { + ui: { + resourceUri: app.resourceUri + } + }, + content: [ + { + text: result.summary, + type: 'text' + } + ], + structuredContent: result + }; + }); + return server; +}; +/** + * Default-exported server factory: `agent-bundle build` detects it and wraps + * this entry in the framework stdio lifecycle shell (console-to-stderr guard, + * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). + */ /* export default */ const mcp_status = (createStatusServer); + + + + + +//#region src/server/stdio.ts +/** +* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. +* +* This transport is only available in Node.js environments. +* +* @example +* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); +* const transport = new StdioServerTransport(); +* await server.connect(transport); +* ``` +*/ +var stdio_StdioServerTransport = class { + _readBuffer; + _started = false; + _closed = false; + constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { + this._stdin = _stdin; + this._stdout = _stdout; + this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); + } + onclose; + onerror; + onmessage; + _ondata = (chunk) => { + try { + this._readBuffer.append(chunk); + this.processReadBuffer(); + } catch (error) { + this.onerror?.(error); + this.close().catch(() => {}); + } + }; + _onerror = (error) => { + this.onerror?.(error); + }; + _onstdouterror = (error) => { + this.onerror?.(error); + this.close().catch(() => {}); + }; + /** + * Starts listening for messages on `stdin`. + */ + async start() { + if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); + this._started = true; + this._stdin.on("data", this._ondata); + this._stdin.on("error", this._onerror); + this._stdout.on("error", this._onstdouterror); + } + processReadBuffer() { + while (true) try { + const message = this._readBuffer.readMessage(); + if (message === null) break; + this.onmessage?.(message); + } catch (error) { + this.onerror?.(error); + } + } + async close() { + if (this._closed) return; + this._closed = true; + this._stdin.off("data", this._ondata); + this._stdin.off("error", this._onerror); + this._stdout.off("error", this._onstdouterror); + if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); + this._readBuffer.clear(); + this.onclose?.(); + } + send(message) { + if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); + return new Promise((resolve, reject) => { + const json = serializeMessage(message); + let settled = false; + const onError = (error) => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + reject(error); + }; + const onDrain = () => { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + this._stdout.off("drain", onDrain); + resolve(); + }; + this._stdout.once("error", onError); + if (this._stdout.write(json)) { + if (settled) return; + settled = true; + this._stdout.off("error", onError); + resolve(); + } else if (!settled) this._stdout.once("drain", onDrain); + }); + } +}; + +//#endregion +//#region src/server/serveStdio.ts +/** +* How long the probe-discard path waits for the probe instance to answer the +* requests it was delivered before closing it. The wait normally settles as +* soon as the DiscoverResult is handed to the wire (or immediately, when a +* delivered cancellation already settled the probe); the bound is a backstop +* so no edge can ever hold the connection's inbound pump indefinitely behind +* the discard. +*/ +const DISCARD_ANSWER_TIMEOUT_MS = 3e3; +/** +* The transport a pinned instance is connected to: a thin channel that writes +* through to the entry-owned wire transport and receives the messages the +* entry forwards. The wire transport itself is never handed to an instance — +* that is what lets the entry discard an optimistic probe instance (close the +* channel) without tearing down the connection. +*/ +var StdioConnectionChannel = class { + onclose; + onerror; + onmessage; + _closed = false; + /** Request ids the entry delivered to the instance that the instance has not yet answered. */ + _pendingRequests = /* @__PURE__ */ new Set(); + _drainWaiters = []; + constructor(_wire, _onInstanceClose, _outboundIntercept) { + this._wire = _wire; + this._onInstanceClose = _onInstanceClose; + this._outboundIntercept = _outboundIntercept; + } + async start() {} + async send(message, options) { + if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { + const { id } = message; + if (id !== void 0) this._settle(id); + } + if (this._closed) return; + if (this._outboundIntercept?.(message) === "handled") return; + return this._wire.send(message, options); + } + setProtocolVersion = (version) => { + this._wire.setProtocolVersion?.(version); + }; + /** Forwards one inbound message to the connected instance. */ + deliver(message, extra) { + if (this._closed) return; + if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); + else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0) this._settle(cancelledId); + } + this.onmessage?.(message, extra); + } + /** + * Resolves once every request delivered to the instance has been answered + * through {@linkcode send}, settled by a delivered cancellation, or the + * channel has been closed and nothing further can be answered. The wait is + * bounded by `timeoutMs` as a backstop so no edge can hold the caller + * indefinitely; resolves `false` only when the bound elapsed with requests + * still unanswered. Used by the probe-discard path so a probe request the + * entry accepted is never silently dropped. + */ + async whenRequestsAnswered(timeoutMs) { + if (this._closed || this._pendingRequests.size === 0) return true; + return await new Promise((resolve) => { + const waiter = () => { + clearTimeout(timer); + resolve(true); + }; + const timer = setTimeout(() => { + this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); + resolve(false); + }, timeoutMs); + this._drainWaiters.push(waiter); + }); + } + async close() { + if (this._closed) return; + this._closed = true; + this._pendingRequests.clear(); + this._releaseDrainWaiters(); + try { + this._onInstanceClose(); + } finally { + this.onclose?.(); + } + } + _settle(id) { + this._pendingRequests.delete(id); + if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); + } + _releaseDrainWaiters() { + const waiters = this._drainWaiters; + this._drainWaiters = []; + for (const waiter of waiters) waiter(); + } +}; +/** +* Classifies one message of the opening exchange with the same body-primary +* rules the HTTP entry applies per request: `initialize` is the legacy +* handshake unless it carries a valid modern envelope claim; a present claim +* is validated (never silently ignored); a claim-less message is 2025-era +* traffic. There is no header layer on stdio, so the body is the only signal. +*/ +function classifyOpeningMessage(message) { + const params = message.params; + if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { + const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; + return { + kind: "legacy", + reason: "initialize", + ...requestedVersion !== void 0 && { requestedVersion } + }; + } + if (!hasEnvelopeClaim(params)) return { + kind: "legacy", + reason: "no-claim" + }; + const meta = requestMetaOf(params); + const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; + if (firstIssue !== void 0) return { + kind: "invalid-envelope", + issue: firstIssue + }; + const claimedVersion = envelopeClaimVersion(params); + if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { + kind: "unsupported-revision", + requested: claimedVersion ?? "unknown" + }; + return { + kind: "modern", + revision: claimedVersion, + classification: { + era: "modern", + revision: claimedVersion + } + }; +} +/** +* Serves MCP over stdio from a server factory, owning the era decision for +* the connection: the opening exchange selects the era, ONE instance from the +* factory is pinned for the connection lifetime, and everything after passes +* straight through to it. See the module documentation for the opening rules. +* +* ```ts +* import { serveStdio } from '@modelcontextprotocol/server/stdio'; +* +* serveStdio(() => { +* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); +* // register tools/resources/prompts once — the same factory serves both eras +* return server; +* }); +* ``` +*/ +function serveStdio(factory, options = {}) { + const legacyMode = options.legacy ?? "serve"; + const wire = options.transport ?? new stdio_StdioServerTransport(); + let state = { phase: "opening" }; + /** Channel currently being discarded (its close must not tear the connection down). */ + let discarding; + let closing = false; + /** + * Whether the connection has been torn down (`handle.close()` or the wire + * closing). The opening arms re-check this after every await: a close can + * race factory construction, and the continuation must neither resurrect + * the connection state nor keep a late-resolved instance around. + */ + const isTornDown = () => closing || state.phase === "closed"; + const reportError = (error) => { + try { + options.onerror?.(error); + } catch {} + }; + const writeErrorResponse = (id, code, message, data) => wire.send({ + jsonrpc: "2.0", + id, + error: { + code, + message, + ...data !== void 0 && { data } + } + }).catch((error) => reportError(stdio_toError(error))); + /** + * Entry-handled `subscriptions/listen` for this connection: holds the + * active subscriptions, serves inbound listen / cancelled-of-listen + * before the pinned instance is consulted, and rewrites the instance's + * outbound change notifications onto the active subscriptions. Only + * consulted on a modern-pinned connection — on a legacy connection + * change notifications pass straight through (the 2025 unsolicited + * delivery model is unchanged). + */ + const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); + /** Outbound intercept installed on a modern instance's channel. */ + const modernOutboundIntercept = (message) => { + if (!isJSONRPCNotification(message)) return void 0; + const routed = listenRouter.routeOutbound(message); + if (routed === "passthrough") return void 0; + for (const stamped of routed) wire.send({ + jsonrpc: "2.0", + ...stamped + }).catch((error) => reportError(stdio_toError(error))); + return "handled"; + }; + /** + * Entry-handled inbound listen routing for a modern-pinned connection. + * Returns `true` when the message was served at the entry and must NOT + * be delivered to the pinned instance. + */ + const tryServeListen = async (message) => { + if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { + const meta = requestMetaOf(message.params); + const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { + key: "_meta", + problem: "the per-request envelope is required on protocol revision 2026-07-28" + }; + const claimedVersion = envelopeClaimVersion(message.params); + let reply; + if (issue !== void 0) reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: -32602, + message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` + } + }; + else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: claimedVersion ?? "unknown" + }); + reply = { + jsonrpc: "2.0", + id: message.id, + error: { + code: error.code, + message: error.message, + data: error.data + } + }; + } else reply = listenRouter.serve(message); + await wire.send("error" in reply ? reply : { + jsonrpc: "2.0", + method: reply.method, + params: reply.params + }).catch((error) => reportError(stdio_toError(error))); + return true; + } + if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { + const cancelledId = message.params?.requestId; + if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; + } + return false; + }; + /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ + const answerLegacyRejection = (request, reason, requestedVersion) => { + const rejection = modernOnlyStrictRejection({ + kind: "legacy", + reason, + ...requestedVersion !== void 0 && { requestedVersion } + }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + if (rejection === void 0) return Promise.resolve(); + reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); + return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); + }; + const onInstanceClosed = (channel) => { + if (closing || channel === discarding) return; + closeAll(); + }; + const connectInstance = async (era, revision) => { + const product = await factory({ era }); + const server = product instanceof McpServer ? product.server : product; + if (era === "modern") { + setNegotiatedProtocolVersion(server, revision); + installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); + listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); + } + const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); + await product.connect(channel); + return { + product, + channel + }; + }; + /** Closes an instance whose factory resolved only after the connection was torn down. */ + const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); + const discardProbeInstance = async (instance) => { + discarding = instance.channel; + try { + if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); + await instance.product.close(); + } catch (error) { + reportError(stdio_toError(error)); + } finally { + discarding = void 0; + } + }; + const processMessage = async (message) => { + if (state.phase === "closed") return; + if (state.phase === "pinned") { + if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { + await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); + return; + } + if (state.era === "modern" && await tryServeListen(message)) return; + state.instance.channel.deliver(message); + return; + } + if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { + reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); + return; + } + const opening = classifyOpeningMessage(message); + switch (opening.kind) { + case "invalid-envelope": { + const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); + else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); + return; + } + case "unsupported-revision": + if (isJSONRPCRequest(message)) { + const error = new UnsupportedProtocolVersionError({ + supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], + requested: opening.requested + }); + reportError(error); + await writeErrorResponse(message.id, error.code, error.message, error.data); + } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); + return; + case "modern": + if (isJSONRPCRequest(message) && message.method === "server/discover") { + if (state.phase === "probe") { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "probe", + instance + }; + instance.channel.deliver(message, { classification: opening.classification }); + return; + } + if (state.phase === "probe") { + if (isJSONRPCNotification(message)) { + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + } + state = { + phase: "pinned", + era: "modern", + instance: state.instance + }; + } else { + const instance = await connectInstance("modern", opening.revision); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "modern", + instance + }; + } + if (await tryServeListen(message)) return; + state.instance.channel.deliver(message, { classification: opening.classification }); + return; + case "legacy": { + if (legacyMode === "reject") { + if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); + return; + } + if (state.phase === "probe") { + await discardProbeInstance(state.instance); + if (isTornDown()) return; + state = { phase: "opening" }; + } + const instance = await connectInstance("legacy"); + if (isTornDown()) { + await disposeLateInstance(instance); + return; + } + state = { + phase: "pinned", + era: "legacy", + instance + }; + state.instance.channel.deliver(message); + return; + } + } + }; + const queue = []; + let pumping = false; + const pump = async () => { + if (pumping) return; + pumping = true; + try { + while (queue.length > 0) { + const message = queue.shift(); + try { + await processMessage(message); + } catch (error) { + if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); + reportError(stdio_toError(error)); + } + } + } finally { + pumping = false; + } + }; + const closeAll = async () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); + if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + await wire.close().catch((error) => reportError(stdio_toError(error))); + }; + wire.onmessage = (message) => { + queue.push(message); + pump(); + }; + wire.onerror = (error) => { + reportError(error); + if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); + }; + wire.onclose = () => { + if (closing || state.phase === "closed") return; + closing = true; + const current = state; + state = { phase: "closed" }; + if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); + }; + const started = wire.start().catch((error) => { + reportError(stdio_toError(error)); + throw error; + }); + started.catch(() => {}); + return { close: async () => { + await started.catch(() => {}); + await closeAll(); + } }; +} +function stdio_toError(value) { + return value instanceof Error ? value : new Error(String(value)); +} + +//#endregion + +//# sourceMappingURL=stdio.mjs.map +const defaultHeartbeatIntervalMs = 300000; +const defaultActivityThrottleMs = 60000; +const defaultShutdownTimeoutMs = 5000; +const defaultHeartbeatName = 'agent-bundle'; +const redirectConsoleToStderr = ()=>{ + const originalStdoutWrite = process.stdout.write.bind(process.stdout); + const stderrConsole = new console.Console({ + stderr: process.stderr, + stdout: process.stderr + }); + const methods = [ + 'debug', + 'dir', + 'error', + 'info', + 'log', + 'trace', + 'warn' + ]; + for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); + process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); + return Object.freeze({ + restoreProtocolStdout: ()=>{ + process.stdout.write = originalStdoutWrite; + } + }); +}; +const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ + const startedAt = Date.now(); + let lastActivityAt = startedAt; + let lastActivityLogAt = 0; + const log = (reason)=>{ + const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); + const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); + writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); + }; + const timer = setInterval(()=>log('interval'), intervalMs); + timer.unref?.(); + return Object.freeze({ + log, + noteActivity: ()=>{ + lastActivityAt = Date.now(); + if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { + lastActivityLogAt = lastActivityAt; + log('activity'); + } + }, + stop: ()=>clearInterval(timer) + }); +}; +const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ + const heartbeat = createHeartbeat({ + ...void 0 === activityThrottleMs ? {} : { + activityThrottleMs + }, + ...void 0 === heartbeatIntervalMs ? {} : { + intervalMs: heartbeatIntervalMs + }, + ...void 0 === serverName ? {} : { + name: serverName + }, + writeLine: heartbeatEnabled ? writeLine : ()=>void 0 + }); + const keepalive = setInterval(()=>void 0, 60000); + keepalive.unref?.(); + let shuttingDown = false; + const shutdown = async (exitCode = 0)=>{ + if (shuttingDown) return; + shuttingDown = true; + signals.off('SIGINT', handleSigint); + signals.off('SIGTERM', handleSigterm); + stdin.off?.('end', handleStdinEnd); + clearInterval(keepalive); + heartbeat.stop(); + await Promise.race([ + Promise.allSettled([ + Promise.resolve().then(()=>transport.close()), + Promise.resolve().then(()=>server.close()) + ]), + new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) + ]); + exit(exitCode); + }; + const handleSigint = ()=>{ + shutdown(130); + }; + const handleSigterm = ()=>{ + shutdown(143); + }; + const handleStdinEnd = ()=>{ + shutdown(0); + }; + signals.on('SIGINT', handleSigint); + signals.on('SIGTERM', handleSigterm); + stdin.once?.('end', handleStdinEnd); + transport.onclose = ()=>{ + shutdown(0); + }; + await server.connect(transport); + const originalOnMessage = transport.onmessage; + transport.onmessage = (message, extra)=>{ + heartbeat.noteActivity(); + originalOnMessage?.(message, extra); + }; + return Object.freeze({ + heartbeat, + shutdown + }); +}; +const runGeneratedStdioMcpEntry = async (options)=>{ + const guard = redirectConsoleToStderr(); + const entry = await options.loadEntry(); + const factory = entry.default; + if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); + const server = await factory(); + const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); + guard.restoreProtocolStdout(); + const transport = new StdioServerTransport(); + return runStdioServer({ + ...options.lifecycle, + server, + serverName: options.serverName, + transport: transport + }); +}; + + + +await runGeneratedStdioMcpEntry({ + loadEntry: ()=>Promise.resolve(status_namespaceObject), + serverName: "status" +}); + +export {}; diff --git a/examples/mcp-app/artifact/portable/plugin.json b/examples/mcp-app/artifact/portable/plugin.json new file mode 100644 index 000000000..e450b6e1e --- /dev/null +++ b/examples/mcp-app/artifact/portable/plugin.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs new file mode 100644 index 000000000..a6f274bf6 --- /dev/null +++ b/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs @@ -0,0 +1,60 @@ +import { readFile } from "node:fs/promises"; + + + + +const healthyCompilerStatus = Object.freeze({ + checks: Object.freeze([ + Object.freeze({ + label: 'Availability', + status: 'passing' + }), + Object.freeze({ + label: 'Build queue', + status: 'passing' + }) + ]), + service: 'compiler', + status: 'healthy', + summary: 'Compiler service is ready for release.' +}); +const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); +const isHealthyCompilerFixture = (value)=>{ + if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { + return false; + } + return healthyCompilerStatus.checks.every((expected, index)=>{ + const received = value.checks[index]; + return isRecord(received) && received.label === expected.label && received.status === expected.status; + }); +}; + + + +const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); +/** + * `agent-bundle build` detects the `main` export and generates the process + * envelope (argv, awaiting, numeric-return exit-code adoption) around it. + */ const main = async ()=>{ + try { + const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); + if (!isHealthyCompilerFixture(fixture)) { + throw new Error('compiler fixture must contain the exact healthy compiler status'); + } + process.stdout.write('Compiler fixture is healthy.\n'); + return 0; + } catch (error) { + process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); + return 1; + } +}; + + +const check_service_fixture_entry_main = main; +if (typeof check_service_fixture_entry_main !== 'function') { + throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/mcp-app/src/scripts/check-service-fixture.ts"); +} +const code = await check_service_fixture_entry_main(process.argv.slice(2)); +if (typeof code === 'number') process.exitCode = code; + +export {}; diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md new file mode 100644 index 000000000..8f91a79d7 --- /dev/null +++ b/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md @@ -0,0 +1,33 @@ +--- +name: service-readiness +description: Reviews service health evidence and records an auditable readiness decision. +--- +# Service readiness + +## When to use + +Use this Skill when a release, incident decision, or service handoff needs a +clear health verdict backed by named checks and current evidence. + +## Required resources + +- Apply [the service status policy](references/status-policy.md) before + classifying a healthy, degraded, or blocked result. +- Deliver the decision with [the readiness report](assets/readiness-report.md). + +## Workflow + +1. Identify the service and collect its current summary and every labelled + check. Record the command, time, result, and evidence source. +2. Classify any failing check with the status policy. A degraded service is not + release-ready until its failing check has an approved mitigation. +3. State the readiness verdict only after confirming availability and the + service-specific release threshold. +4. Complete the report with the status, checks, evidence, owner, and next + action. Do not omit a failing check from the final decision. + +## Final report requirements + +State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the +service summary; list each labelled check and its status; identify the owner +and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md new file mode 100644 index 000000000..3da5d52ea --- /dev/null +++ b/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md @@ -0,0 +1,22 @@ +# Service readiness report + +## Verdict + +State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. + +## Evidence + +Record the collection time, command or artifact, service summary, and source. + +## Checks + +List every labelled check with its observed status and release threshold. + +## Findings and mitigation + +For each non-passing check, record the impact, owner, mitigation, due date, +and the evidence required to clear it. + +## Next action + +Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md new file mode 100644 index 000000000..7e5766172 --- /dev/null +++ b/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md @@ -0,0 +1,22 @@ +# Service status policy + +## Evidence standard + +Readiness evidence must identify the service, collection time, check label, +observed status, and source command or artifact. Missing or stale evidence is +not a passing check. + +## Status classification + +- **Healthy**: every required release check is passing. +- **Degraded**: availability remains sufficient, but a release threshold such + as P95 latency is failing. Record an owner and mitigation before release. +- **Blocked**: availability or a critical safety check is failing. Do not + release until new passing evidence is collected. +- **Needs evidence**: the service or any required check cannot be verified. + +## Release decision + +Issue `ready` only for a healthy service with current evidence. A degraded +service needs an explicit mitigation decision; a blocked service cannot pass; +and missing evidence requires a new check rather than an assumption. diff --git a/examples/skills-starter/artifact/agent-bundle.hooks.json b/examples/skills-starter/artifact/agent-bundle.hooks.json new file mode 100644 index 000000000..a41e820b1 --- /dev/null +++ b/examples/skills-starter/artifact/agent-bundle.hooks.json @@ -0,0 +1 @@ +{"hooks":[]} diff --git a/examples/skills-starter/artifact/agent-bundle.manifest.json b/examples/skills-starter/artifact/agent-bundle.manifest.json new file mode 100644 index 000000000..dd6e9fecb --- /dev/null +++ b/examples/skills-starter/artifact/agent-bundle.manifest.json @@ -0,0 +1 @@ +{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":13,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"4df87c0d55ad1cbfddaadb62a690a467c4a2661d5da94697caefe9492a0e01b5","sourceInputs":["agent-bundle.config.ts"]},{"bytes":358,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"173c38e9dad7ec0bc9f48f850307206bda76817250f88ee71f8148cf84232013","sourceInputs":["agent-bundle.config.ts"]},{"bytes":187,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"6c214932fd8a194629570beaf09f03b5674235b3825244e41b94ac85925a17e8","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":473,"kind":"generated","path":"claude/INSTALL.md","sha256":"05237956c42069fe4812a300076665b81926069a77eecf373c4759eb73777a94","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"claude/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"claude/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"claude/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"claude/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"claude/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"claude/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"claude/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"claude/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"claude/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"claude/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":255,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"92a763708bcf83d61e127c6cb01b53004d73ba77e976b18c0be957d26ec4041e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":611,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"d1e15bed8bff1408dd3b254473067c0411862584b358eef88ebcbd3cd59472bc","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":361,"kind":"generated","path":"codex/INSTALL.md","sha256":"f67365c3cd57f48d62a2f182fb250b5cd334206100a4cc643e8bdf81a1f1dfe2","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"codex/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"codex/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"codex/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"codex/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"codex/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"codex/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"codex/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"codex/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"codex/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"codex/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":704,"kind":"generated","path":"portable/INSTALL.md","sha256":"36fcad70168df8ba84710412655ff3baf636f8228357e31f3f4f22aeea4e2ef4","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3308,"kind":"generated","path":"portable/install.mjs","sha256":"86a297294bf7f79001860d0d2bdd496d7bccf16a94201456f97926c3a8c3eff0","sourceInputs":["agent-bundle.config.ts"]},{"bytes":223,"kind":"generated","path":"portable/plugin.json","sha256":"bf4244be5133884977cdf0b957194f7eae0a0058abeda47916200ffd6c1a303d","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"portable/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"portable/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"portable/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"portable/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"portable/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"portable/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"portable/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"portable/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"portable/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"portable/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a","configPath":"agent-bundle.config.ts","modelDigest":"2c1281c98b2a03bbb8d8584df134d7acce0047f52a3f7abbad5b7239577cbc7a","packageName":"@agent-bundle-example/skills-starter","revision":"efe0374fe3133180d89726cb4f815e148717e618e2d08f57cdef9cb4b0d5387e","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a"},{"executable":false,"path":"evals/engineering-operations.eval.ts","sha256":"60882b3746d4cd258d66d579757935f39666a6e610e86a3dbf7858807a516d69"},{"executable":false,"path":"evals/fixtures/incident/result.json","sha256":"57431bcbff2673ff2cf95f1a1dbccd063b2293b8be8bbc47b235d46f0686659d"},{"executable":false,"path":"evals/fixtures/release/result.json","sha256":"c2a2ddd2207fe2f6da264310c508d1d0384abf76d49ad796fbefcc10eb336905"},{"executable":false,"path":"evals/fixtures/upgrade/result.json","sha256":"9442378ddea4c0880d7a920ee575ed4d06cddae4b305ec403e5d95d03a4a6021"},{"executable":false,"path":"evals/graders/operations-result.ts","sha256":"476c2ca6d8937b8240384af2de0cb2036fc1a72d7cbf715f33142a6427d34471"},{"executable":false,"path":"evals/graders/release-result.ts","sha256":"c9cfcc05e760c5d672685a0a79ccbf96f532674d3e044fbce78328413f0ae06b"},{"executable":false,"path":"evals/release-readiness.eval.ts","sha256":"aa76a5bd2a0c88c0a66952d273cf8c3dd6858598eeea38853123b7b853b1fe1b"},{"executable":false,"path":"package.json","sha256":"2ad66bb88761179c61d171f49cfedec417bdb8c552201772737e54105297cdfb"},{"executable":false,"path":"README.md","sha256":"99f3588b978f59fd41971fd15911426da8d1cdff98fa531bb1f6c1e80b23c744"},{"executable":false,"path":"src/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff"},{"executable":false,"path":"src/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb"},{"executable":false,"path":"src/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69"},{"executable":false,"path":"src/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce"},{"executable":false,"path":"src/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea"},{"executable":false,"path":"src/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7"},{"executable":false,"path":"src/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88"},{"executable":false,"path":"src/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6"},{"executable":false,"path":"src/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88"},{"executable":false,"path":"src/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.7.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"1d43c5ed19de401fb7455c5912e4c21113f6e387aef4c28d2eca121f7554c4e8"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"986bcafa6ef46f9dc4558f05781f53400b3d75533a075068184ba8d43670d4ec"}]},{"adapterRevision":"1.5.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json b/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json new file mode 100644 index 000000000..24cb4579e --- /dev/null +++ b/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json @@ -0,0 +1 @@ +{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter-marketplace","owner":{"name":"skills-starter"},"plugins":[{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","source":"./","version":"1.0.0"}]} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json b/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json new file mode 100644 index 000000000..0ef4b4869 --- /dev/null +++ b/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/claude/INSTALL.md b/examples/skills-starter/artifact/claude/INSTALL.md new file mode 100644 index 000000000..e5e449b39 --- /dev/null +++ b/examples/skills-starter/artifact/claude/INSTALL.md @@ -0,0 +1,18 @@ +# Install skills-starter + +A practical engineering operations bundle for incidents, dependency upgrades, and releases. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Claude Code + +Claude Code installs this bundle through its local marketplace contract: + +```sh +claude plugin marketplace add ./ +claude plugin install skills-starter@skills-starter-marketplace --scope user +``` + +Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md new file mode 100644 index 000000000..5f91ab96e --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md @@ -0,0 +1,33 @@ +--- +name: dependency-upgrade +description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. +--- +# Dependency upgrade + +## When to use + +Use this Skill for a library, runtime, toolchain, or platform upgrade that can +change public APIs, generated output, operational behavior, or support policy. + +## Required resources + +- Apply [the compatibility checklist](references/compatibility-checklist.md). +- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). + +## Workflow + +1. Record the current and proposed versions, why the change is needed, and the + supported runtime/package-manager matrix. +2. Read primary release notes and migration guides. List removed APIs, default + changes, peer requirements, and known regressions that intersect this repo. +3. Map affected imports, configuration, generated artifacts, consumers, and + CI/release surfaces before editing. +4. Implement the smallest coherent increment and run focused contract tests, + type checks, production builds, and packed-consumer checks. +5. Define rollout signals and a tested rollback path. Do not call the upgrade + complete until shipped output and a real consumer both pass. + +## Final answer + +State the compatibility decision, changed surfaces, evidence run, remaining +risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md new file mode 100644 index 000000000..15ed88f24 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md @@ -0,0 +1,21 @@ +# Dependency upgrade plan + +## Decision + +Current version, target version, motivation, and compatibility verdict. + +## Affected surfaces + +Imports, configuration, generated output, consumers, CI, and release tooling. + +## Implementation increments + +Each increment, its tests, and its reversible boundary. + +## Verification + +Commands, observed results, and packed or browser consumer evidence. + +## Rollout and rollback + +Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md new file mode 100644 index 000000000..51ac5226a --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md @@ -0,0 +1,9 @@ +# Compatibility checklist + +- Runtime and package-manager support matrix is explicit. +- Direct, peer, optional, and transitive dependency effects are understood. +- Configuration defaults and removed/deprecated APIs are accounted for. +- Generated files and package exports remain deterministic. +- Type checks, focused tests, production builds, and packed consumers pass. +- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. +- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md new file mode 100644 index 000000000..e91f53773 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md @@ -0,0 +1,34 @@ +--- +name: incident-triage +description: Triages production incidents with evidence-first containment and a clear operational handoff. +--- +# Incident triage + +## When to use + +Use this Skill when an alert, customer report, or operator observation suggests +an active production incident and the team needs a fast, auditable first pass. + +## Required resources + +- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. +- Record the handoff with [the incident update template](assets/incident-update.md). + +## Workflow + +1. Establish impact: affected users, services, regions, start time, and the + strongest known symptom. Separate observed facts from hypotheses. +2. Preserve evidence before changing the system: relevant request IDs, logs, + metrics, deploys, feature flags, and dependency health. +3. Choose the smallest reversible containment action. State its expected signal + and rollback condition before executing it. +4. Re-evaluate impact after containment. Escalate when severity, ownership, or + blast radius remains uncertain. +5. Produce an incident update with timeline, current impact, actions, owners, + open questions, and the next update time. + +## Guardrails + +- Never claim root cause from correlation alone. +- Never expose credentials, customer payloads, or private identifiers. +- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md new file mode 100644 index 000000000..1e2b7529f --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md @@ -0,0 +1,9 @@ +# Incident update + +- **Status:** investigating | identified | monitoring | resolved +- **Impact:** users, services, regions, and start time +- **Observed evidence:** metrics, logs, requests, and recent changes +- **Actions taken:** action, owner, result, and rollback state +- **Current hypothesis:** clearly marked as confirmed or unconfirmed +- **Next steps:** owner and expected completion +- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md new file mode 100644 index 000000000..d98d8a283 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md @@ -0,0 +1,9 @@ +# First 30 minutes + +1. Acknowledge the incident and name an incident lead. +2. Capture the first known bad time and a comparable known-good baseline. +3. Check recent deploys, configuration changes, dependency status, and capacity. +4. Identify one measurable containment hypothesis and its rollback signal. +5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. + +Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md b/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md new file mode 100644 index 000000000..085376189 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md @@ -0,0 +1,34 @@ +--- +name: release-review +description: Reviews release evidence and issues an auditable readiness verdict. +--- +# Release review + +## When to use + +Use this Skill when a release candidate needs a go/no-go verdict supported by +checked, reproducible evidence. + +## Required resources + +- Read [the release checklist](references/checklist.md) to inspect the artifact. +- Apply [the release readiness policy](references/release-policy.md) to classify findings. +- Deliver the result with [the release readiness report template](assets/report-template.md). + +## Workflow + +1. Gather evidence for each checklist item. Cite the command, artifact path, + observed result, and reproduction steps for every finding. +2. Classify each finding using the policy severity. A blocker prevents a + `ready` verdict; unresolved non-blockers must still be disclosed. +3. Decide the verdict only after all required evidence is recorded. Use + `ready` only when there are no blockers. +4. Complete every section of the report template: verdict, evidence, findings, + blockers, and required follow-up. + +## Final report requirements + +The final report must state `ready`, `not ready`, or `needs evidence`; list +all evidence reviewed; give each finding a severity and reproduction; and make +the blocker count explicit. Do not issue `ready` when evidence is missing or a +blocker remains. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md new file mode 100644 index 000000000..76fb83fc7 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md @@ -0,0 +1,22 @@ +# Release readiness report + +## Verdict + +State `ready`, `not ready`, or `needs evidence`, and give the blocker count. + +## Evidence reviewed + +For each check, record the command, artifact path, observed result, and date. + +## Findings + +List each concrete issue, its severity, impact, owner, and reproduction. + +## Blockers + +List every unresolved blocker, or state `None`. + +## Required follow-up + +Record the owner, mitigation, and decision date for every unresolved Major or +Minor finding. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md new file mode 100644 index 000000000..823e865a9 --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md @@ -0,0 +1,8 @@ +# Release checklist + +1. Confirm the release artifact contains the documented public entrypoints. +2. Confirm generated files are reproducible from the checked-in sources. +3. Run the documented validation, build, and deterministic evaluation commands. +4. Record the command, artifact path, observed output, and reproduction for + every defect. +5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md new file mode 100644 index 000000000..09ceb86ba --- /dev/null +++ b/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md @@ -0,0 +1,22 @@ +# Release readiness policy + +## Evidence standard + +Release evidence must be specific, reproducible, and tied to the candidate: +record the command, artifact path, observed result, and reproduction steps. +Missing or stale evidence is not proof of readiness. + +## Severity + +- **Blocker**: prevents safe release, violates a documented contract, or has no + viable mitigation. Any blocker requires a `not ready` verdict. +- **Major**: materially degrades a supported workflow. It must have an owner, + mitigation, and release decision recorded in the report. +- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent + `ready` when its evidence and owner are recorded. + +## Verdict policy + +Issue `ready` only when all required evidence is current and the blocker list +is empty. Issue `needs evidence` when required evidence is absent, stale, or +cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json b/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json new file mode 100644 index 000000000..b3a1fadbc --- /dev/null +++ b/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json @@ -0,0 +1 @@ +{"interface":{"displayName":"skills-starter"},"name":"skills-starter-marketplace","plugins":[{"category":"Productivity","name":"skills-starter","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json b/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json new file mode 100644 index 000000000..44161e85b --- /dev/null +++ b/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json @@ -0,0 +1 @@ +{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","interface":{"capabilities":["skills"],"category":"Productivity","defaultPrompt":["Help me use skills-starter."],"developerName":"skills-starter","displayName":"skills-starter","longDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","shortDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases."},"name":"skills-starter","skills":"./skills/","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/codex/INSTALL.md b/examples/skills-starter/artifact/codex/INSTALL.md new file mode 100644 index 000000000..0c56ee69d --- /dev/null +++ b/examples/skills-starter/artifact/codex/INSTALL.md @@ -0,0 +1,16 @@ +# Install skills-starter + +A practical engineering operations bundle for incidents, dependency upgrades, and releases. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Codex + +Codex installs this bundle from its local marketplace snapshot: + +```sh +codex plugin marketplace add ./ +codex plugin add skills-starter@skills-starter-marketplace +``` diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md new file mode 100644 index 000000000..5f91ab96e --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md @@ -0,0 +1,33 @@ +--- +name: dependency-upgrade +description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. +--- +# Dependency upgrade + +## When to use + +Use this Skill for a library, runtime, toolchain, or platform upgrade that can +change public APIs, generated output, operational behavior, or support policy. + +## Required resources + +- Apply [the compatibility checklist](references/compatibility-checklist.md). +- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). + +## Workflow + +1. Record the current and proposed versions, why the change is needed, and the + supported runtime/package-manager matrix. +2. Read primary release notes and migration guides. List removed APIs, default + changes, peer requirements, and known regressions that intersect this repo. +3. Map affected imports, configuration, generated artifacts, consumers, and + CI/release surfaces before editing. +4. Implement the smallest coherent increment and run focused contract tests, + type checks, production builds, and packed-consumer checks. +5. Define rollout signals and a tested rollback path. Do not call the upgrade + complete until shipped output and a real consumer both pass. + +## Final answer + +State the compatibility decision, changed surfaces, evidence run, remaining +risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md new file mode 100644 index 000000000..15ed88f24 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md @@ -0,0 +1,21 @@ +# Dependency upgrade plan + +## Decision + +Current version, target version, motivation, and compatibility verdict. + +## Affected surfaces + +Imports, configuration, generated output, consumers, CI, and release tooling. + +## Implementation increments + +Each increment, its tests, and its reversible boundary. + +## Verification + +Commands, observed results, and packed or browser consumer evidence. + +## Rollout and rollback + +Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md new file mode 100644 index 000000000..51ac5226a --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md @@ -0,0 +1,9 @@ +# Compatibility checklist + +- Runtime and package-manager support matrix is explicit. +- Direct, peer, optional, and transitive dependency effects are understood. +- Configuration defaults and removed/deprecated APIs are accounted for. +- Generated files and package exports remain deterministic. +- Type checks, focused tests, production builds, and packed consumers pass. +- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. +- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md new file mode 100644 index 000000000..e91f53773 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md @@ -0,0 +1,34 @@ +--- +name: incident-triage +description: Triages production incidents with evidence-first containment and a clear operational handoff. +--- +# Incident triage + +## When to use + +Use this Skill when an alert, customer report, or operator observation suggests +an active production incident and the team needs a fast, auditable first pass. + +## Required resources + +- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. +- Record the handoff with [the incident update template](assets/incident-update.md). + +## Workflow + +1. Establish impact: affected users, services, regions, start time, and the + strongest known symptom. Separate observed facts from hypotheses. +2. Preserve evidence before changing the system: relevant request IDs, logs, + metrics, deploys, feature flags, and dependency health. +3. Choose the smallest reversible containment action. State its expected signal + and rollback condition before executing it. +4. Re-evaluate impact after containment. Escalate when severity, ownership, or + blast radius remains uncertain. +5. Produce an incident update with timeline, current impact, actions, owners, + open questions, and the next update time. + +## Guardrails + +- Never claim root cause from correlation alone. +- Never expose credentials, customer payloads, or private identifiers. +- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md new file mode 100644 index 000000000..1e2b7529f --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md @@ -0,0 +1,9 @@ +# Incident update + +- **Status:** investigating | identified | monitoring | resolved +- **Impact:** users, services, regions, and start time +- **Observed evidence:** metrics, logs, requests, and recent changes +- **Actions taken:** action, owner, result, and rollback state +- **Current hypothesis:** clearly marked as confirmed or unconfirmed +- **Next steps:** owner and expected completion +- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md new file mode 100644 index 000000000..d98d8a283 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md @@ -0,0 +1,9 @@ +# First 30 minutes + +1. Acknowledge the incident and name an incident lead. +2. Capture the first known bad time and a comparable known-good baseline. +3. Check recent deploys, configuration changes, dependency status, and capacity. +4. Identify one measurable containment hypothesis and its rollback signal. +5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. + +Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md b/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md new file mode 100644 index 000000000..085376189 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md @@ -0,0 +1,34 @@ +--- +name: release-review +description: Reviews release evidence and issues an auditable readiness verdict. +--- +# Release review + +## When to use + +Use this Skill when a release candidate needs a go/no-go verdict supported by +checked, reproducible evidence. + +## Required resources + +- Read [the release checklist](references/checklist.md) to inspect the artifact. +- Apply [the release readiness policy](references/release-policy.md) to classify findings. +- Deliver the result with [the release readiness report template](assets/report-template.md). + +## Workflow + +1. Gather evidence for each checklist item. Cite the command, artifact path, + observed result, and reproduction steps for every finding. +2. Classify each finding using the policy severity. A blocker prevents a + `ready` verdict; unresolved non-blockers must still be disclosed. +3. Decide the verdict only after all required evidence is recorded. Use + `ready` only when there are no blockers. +4. Complete every section of the report template: verdict, evidence, findings, + blockers, and required follow-up. + +## Final report requirements + +The final report must state `ready`, `not ready`, or `needs evidence`; list +all evidence reviewed; give each finding a severity and reproduction; and make +the blocker count explicit. Do not issue `ready` when evidence is missing or a +blocker remains. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md new file mode 100644 index 000000000..76fb83fc7 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md @@ -0,0 +1,22 @@ +# Release readiness report + +## Verdict + +State `ready`, `not ready`, or `needs evidence`, and give the blocker count. + +## Evidence reviewed + +For each check, record the command, artifact path, observed result, and date. + +## Findings + +List each concrete issue, its severity, impact, owner, and reproduction. + +## Blockers + +List every unresolved blocker, or state `None`. + +## Required follow-up + +Record the owner, mitigation, and decision date for every unresolved Major or +Minor finding. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md new file mode 100644 index 000000000..823e865a9 --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md @@ -0,0 +1,8 @@ +# Release checklist + +1. Confirm the release artifact contains the documented public entrypoints. +2. Confirm generated files are reproducible from the checked-in sources. +3. Run the documented validation, build, and deterministic evaluation commands. +4. Record the command, artifact path, observed output, and reproduction for + every defect. +5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md new file mode 100644 index 000000000..09ceb86ba --- /dev/null +++ b/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md @@ -0,0 +1,22 @@ +# Release readiness policy + +## Evidence standard + +Release evidence must be specific, reproducible, and tied to the candidate: +record the command, artifact path, observed result, and reproduction steps. +Missing or stale evidence is not proof of readiness. + +## Severity + +- **Blocker**: prevents safe release, violates a documented contract, or has no + viable mitigation. Any blocker requires a `not ready` verdict. +- **Major**: materially degrades a supported workflow. It must have an owner, + mitigation, and release decision recorded in the report. +- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent + `ready` when its evidence and owner are recorded. + +## Verdict policy + +Issue `ready` only when all required evidence is current and the blocker list +is empty. Issue `needs evidence` when required evidence is absent, stale, or +cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/portable/INSTALL.md b/examples/skills-starter/artifact/portable/INSTALL.md new file mode 100644 index 000000000..bf452980c --- /dev/null +++ b/examples/skills-starter/artifact/portable/INSTALL.md @@ -0,0 +1,19 @@ +# Install skills-starter + +A practical engineering operations bundle for incidents, dependency upgrades, and releases. + +Version: `1.0.0` + +Run these commands from this bundle directory. + +## Portable Agent Plugin + +Portable is a distribution profile, not a host runtime with one universal install location. +This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). +Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run +`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT +are also native clients. The bundled installer provides the Cursor local copy: + +```sh +node ./install.mjs +``` diff --git a/examples/skills-starter/artifact/portable/install.mjs b/examples/skills-starter/artifact/portable/install.mjs new file mode 100644 index 000000000..51b9b39a7 --- /dev/null +++ b/examples/skills-starter/artifact/portable/install.mjs @@ -0,0 +1,80 @@ +#!/usr/bin/env node +import { createHash } from 'node:crypto'; +import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; +import { homedir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const pluginName = "skills-starter"; +const pluginVersion = "1.0.0"; +const source = resolve(fileURLToPath(new URL('.', import.meta.url))); +const cursorRoot = join(homedir(), '.cursor'); +const installRoot = join(cursorRoot, 'plugins', 'local'); +const destination = join(installRoot, pluginName); + +const exists = async (path) => { + try { await lstat(path); return true; } + catch (error) { if (error?.code === 'ENOENT') return false; throw error; } +}; + +const treeHash = async (root, prefix = '') => { + const rootMetadata = await lstat(root); + if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { + throw new Error('Refusing unsupported filesystem entry ".".'); + } + const hash = createHash('sha256'); + const visit = async (relative) => { + const absolute = join(root, relative); + const metadata = await lstat(absolute); + if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { + throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); + } + if (metadata.isDirectory()) { + for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); + return; + } + hash.update(relative.replaceAll('\\', '/')); + hash.update('\0'); + hash.update(await readFile(absolute)); + hash.update('\0'); + }; + for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); + return hash.digest('hex'); +}; + +const installedVersion = async () => { + for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { + try { + const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); + if (typeof value.version === 'string') return value.version; + } catch (error) { if (error?.code !== 'ENOENT') throw error; } + } + return undefined; +}; + +if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { + throw new Error(`Cursor is not installed in ${cursorRoot}.`); +} +await mkdir(installRoot, { recursive: true }); +if (await exists(destination)) { + const currentVersion = await installedVersion(); + if (currentVersion !== undefined && currentVersion !== pluginVersion) { + throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); + } + if (source === destination || await treeHash(source) === await treeHash(destination)) { + console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); + process.exit(0); + } + throw new Error(`Refusing content collision at ${destination}.`); +} + +const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); +const stage = join(stageParent, 'bundle'); +try { + await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); + await treeHash(stage); + await rename(stage, destination); + console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); +} finally { + await rm(stageParent, { force: true, recursive: true }); +} diff --git a/examples/skills-starter/artifact/portable/plugin.json b/examples/skills-starter/artifact/portable/plugin.json new file mode 100644 index 000000000..42585f082 --- /dev/null +++ b/examples/skills-starter/artifact/portable/plugin.json @@ -0,0 +1 @@ +{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md new file mode 100644 index 000000000..5f91ab96e --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md @@ -0,0 +1,33 @@ +--- +name: dependency-upgrade +description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. +--- +# Dependency upgrade + +## When to use + +Use this Skill for a library, runtime, toolchain, or platform upgrade that can +change public APIs, generated output, operational behavior, or support policy. + +## Required resources + +- Apply [the compatibility checklist](references/compatibility-checklist.md). +- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). + +## Workflow + +1. Record the current and proposed versions, why the change is needed, and the + supported runtime/package-manager matrix. +2. Read primary release notes and migration guides. List removed APIs, default + changes, peer requirements, and known regressions that intersect this repo. +3. Map affected imports, configuration, generated artifacts, consumers, and + CI/release surfaces before editing. +4. Implement the smallest coherent increment and run focused contract tests, + type checks, production builds, and packed-consumer checks. +5. Define rollout signals and a tested rollback path. Do not call the upgrade + complete until shipped output and a real consumer both pass. + +## Final answer + +State the compatibility decision, changed surfaces, evidence run, remaining +risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md new file mode 100644 index 000000000..15ed88f24 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md @@ -0,0 +1,21 @@ +# Dependency upgrade plan + +## Decision + +Current version, target version, motivation, and compatibility verdict. + +## Affected surfaces + +Imports, configuration, generated output, consumers, CI, and release tooling. + +## Implementation increments + +Each increment, its tests, and its reversible boundary. + +## Verification + +Commands, observed results, and packed or browser consumer evidence. + +## Rollout and rollback + +Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md new file mode 100644 index 000000000..51ac5226a --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md @@ -0,0 +1,9 @@ +# Compatibility checklist + +- Runtime and package-manager support matrix is explicit. +- Direct, peer, optional, and transitive dependency effects are understood. +- Configuration defaults and removed/deprecated APIs are accounted for. +- Generated files and package exports remain deterministic. +- Type checks, focused tests, production builds, and packed consumers pass. +- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. +- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md new file mode 100644 index 000000000..e91f53773 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md @@ -0,0 +1,34 @@ +--- +name: incident-triage +description: Triages production incidents with evidence-first containment and a clear operational handoff. +--- +# Incident triage + +## When to use + +Use this Skill when an alert, customer report, or operator observation suggests +an active production incident and the team needs a fast, auditable first pass. + +## Required resources + +- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. +- Record the handoff with [the incident update template](assets/incident-update.md). + +## Workflow + +1. Establish impact: affected users, services, regions, start time, and the + strongest known symptom. Separate observed facts from hypotheses. +2. Preserve evidence before changing the system: relevant request IDs, logs, + metrics, deploys, feature flags, and dependency health. +3. Choose the smallest reversible containment action. State its expected signal + and rollback condition before executing it. +4. Re-evaluate impact after containment. Escalate when severity, ownership, or + blast radius remains uncertain. +5. Produce an incident update with timeline, current impact, actions, owners, + open questions, and the next update time. + +## Guardrails + +- Never claim root cause from correlation alone. +- Never expose credentials, customer payloads, or private identifiers. +- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md new file mode 100644 index 000000000..1e2b7529f --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md @@ -0,0 +1,9 @@ +# Incident update + +- **Status:** investigating | identified | monitoring | resolved +- **Impact:** users, services, regions, and start time +- **Observed evidence:** metrics, logs, requests, and recent changes +- **Actions taken:** action, owner, result, and rollback state +- **Current hypothesis:** clearly marked as confirmed or unconfirmed +- **Next steps:** owner and expected completion +- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md new file mode 100644 index 000000000..d98d8a283 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md @@ -0,0 +1,9 @@ +# First 30 minutes + +1. Acknowledge the incident and name an incident lead. +2. Capture the first known bad time and a comparable known-good baseline. +3. Check recent deploys, configuration changes, dependency status, and capacity. +4. Identify one measurable containment hypothesis and its rollback signal. +5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. + +Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md b/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md new file mode 100644 index 000000000..085376189 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md @@ -0,0 +1,34 @@ +--- +name: release-review +description: Reviews release evidence and issues an auditable readiness verdict. +--- +# Release review + +## When to use + +Use this Skill when a release candidate needs a go/no-go verdict supported by +checked, reproducible evidence. + +## Required resources + +- Read [the release checklist](references/checklist.md) to inspect the artifact. +- Apply [the release readiness policy](references/release-policy.md) to classify findings. +- Deliver the result with [the release readiness report template](assets/report-template.md). + +## Workflow + +1. Gather evidence for each checklist item. Cite the command, artifact path, + observed result, and reproduction steps for every finding. +2. Classify each finding using the policy severity. A blocker prevents a + `ready` verdict; unresolved non-blockers must still be disclosed. +3. Decide the verdict only after all required evidence is recorded. Use + `ready` only when there are no blockers. +4. Complete every section of the report template: verdict, evidence, findings, + blockers, and required follow-up. + +## Final report requirements + +The final report must state `ready`, `not ready`, or `needs evidence`; list +all evidence reviewed; give each finding a severity and reproduction; and make +the blocker count explicit. Do not issue `ready` when evidence is missing or a +blocker remains. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md new file mode 100644 index 000000000..76fb83fc7 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md @@ -0,0 +1,22 @@ +# Release readiness report + +## Verdict + +State `ready`, `not ready`, or `needs evidence`, and give the blocker count. + +## Evidence reviewed + +For each check, record the command, artifact path, observed result, and date. + +## Findings + +List each concrete issue, its severity, impact, owner, and reproduction. + +## Blockers + +List every unresolved blocker, or state `None`. + +## Required follow-up + +Record the owner, mitigation, and decision date for every unresolved Major or +Minor finding. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md new file mode 100644 index 000000000..823e865a9 --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md @@ -0,0 +1,8 @@ +# Release checklist + +1. Confirm the release artifact contains the documented public entrypoints. +2. Confirm generated files are reproducible from the checked-in sources. +3. Run the documented validation, build, and deterministic evaluation commands. +4. Record the command, artifact path, observed output, and reproduction for + every defect. +5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md new file mode 100644 index 000000000..09ceb86ba --- /dev/null +++ b/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md @@ -0,0 +1,22 @@ +# Release readiness policy + +## Evidence standard + +Release evidence must be specific, reproducible, and tied to the candidate: +record the command, artifact path, observed result, and reproduction steps. +Missing or stale evidence is not proof of readiness. + +## Severity + +- **Blocker**: prevents safe release, violates a documented contract, or has no + viable mitigation. Any blocker requires a `not ready` verdict. +- **Major**: materially degrades a supported workflow. It must have an owner, + mitigation, and release decision recorded in the report. +- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent + `ready` when its evidence and owner are recorded. + +## Verdict policy + +Issue `ready` only when all required evidence is current and the blocker list +is empty. Issue `needs evidence` when required evidence is absent, stale, or +cannot be reproduced. Otherwise issue `not ready`. diff --git a/packages/agent-bundle/src/test/registry.ts b/packages/agent-bundle/src/test/registry.ts index e7927820a..7234b924b 100644 --- a/packages/agent-bundle/src/test/registry.ts +++ b/packages/agent-bundle/src/test/registry.ts @@ -16,7 +16,12 @@ export const AGENT_TEST_REGISTRY_SYMBOL_KEY = 'agent-bundle/test-route-registry' const REGISTRY_SYMBOL = Symbol.for(AGENT_TEST_REGISTRY_SYMBOL_KEY); -export const AGENT_TEST_REGISTRY_VERSION = 3; +/** + * Bumped whenever the registry layout changes so a setup module and the + * helpers reading it never silently disagree about what the registry carries. + * 4: `providerLoaders` (conventional context providers mounted by the harness). + */ +export const AGENT_TEST_REGISTRY_VERSION = 4; export type AgentStateModuleLoader = () => Promise<{ readonly default: AgentStateDefinition; diff --git a/packages/agent-bundle/src/test/render.ts b/packages/agent-bundle/src/test/render.ts index 7100866f0..2bd7bd99d 100644 --- a/packages/agent-bundle/src/test/render.ts +++ b/packages/agent-bundle/src/test/render.ts @@ -215,9 +215,45 @@ const cliArguments = ( ); }; +/** + * The executable surface name the generated entry records and hands to + * providers, derived like the artifact derives it: a routed CLI command is + * its space-joined command path (`tooling report`), a script is its + * path-derived name (`script:tooling-summary` -> `tooling-summary`), and an + * event route is its canonical event. The compiled command graph is the + * authority for command paths; without a manifest (module-direct renders) + * the harness falls back to the route id's own path segments. + */ +const executableSurface = ( + kind: RenderableRouteKind, + routeId: string, + manifest: AgentBundleTestManifest | undefined, +): string => { + switch (kind) { + case 'prompt': + case 'resource': + case 'tool': + return protocolName(routeId); + case 'event-route': + return routeId.startsWith('event:') ? routeId.slice('event:'.length) : routeId; + case 'cli': { + const command = manifest?.cliCommands.find((candidate) => candidate.routeId === routeId); + if (command !== undefined) return command.path.join(' '); + return (routeId.startsWith('cli:') ? routeId.slice('cli:'.length) : routeId).replaceAll('/', ' '); + } + case 'script': + return routeId.startsWith('script:') ? routeId.slice('script:'.length) : routeId; + default: { + const exhaustive: never = kind; + throw new AgentTestError('unsupported-route-kind', `Unsupported renderable route kind ${String(exhaustive)}.`); + } + } +}; + const invocationFor = ( kind: RenderableRouteKind, routeId: string, + surface: string, options: RenderRouteOptions, provenance: RenderedRouteProvenance, ): AgentRenderInvocation => { @@ -233,20 +269,14 @@ const invocationFor = ( // The generated server names the canonical event, not the route id, and // carries the host envelope as `payload`; the harness matches both so a // route sees the props the artifact would hand it. - return { - kind: 'event', - props: { - event: routeId.startsWith('event:') ? routeId.slice('event:'.length) : routeId, - payload: (options.input ?? {}) as never, - }, - }; + return { kind: 'event', props: { event: surface, payload: (options.input ?? {}) as never } }; case 'cli': - return { kind: 'cli', props: { args: cliArguments(options, provenance), command: routeId } }; + // The generated executable passes `command.path.join(' ')`, never the + // route id, so providers branching on `command` see the artifact's value. + return { kind: 'cli', props: { args: cliArguments(options, provenance), command: surface } }; case 'script': - return { - kind: 'script', - props: { input: cliArguments(options, provenance) as never, name: routeId }, - }; + // The generated script passes its path-derived name (`tooling-summary`). + return { kind: 'script', props: { input: cliArguments(options, provenance) as never, name: surface } }; default: { const exhaustive: never = kind; throw new AgentTestError( @@ -313,14 +343,20 @@ const componentProps = ( } }; -/** The request-scope invocation the generated server opens for one route. */ +/** + * The request-scope invocation the generated entry opens for one route: + * `operationId` is the route id and `surface` the executable surface name on + * every kind, exactly as the generated MCP server, CLI, and script shells + * record them. + */ const requestInvocation = ( invocation: AgentRenderInvocation, routeId: string, + surface: string, ): AgentInvocationInput => ({ kind: invocation.kind, - ...(invocation.kind === 'tool' ? { operationId: routeId } : {}), - surface: invocation.kind === 'tool' ? protocolName(routeId) : routeId, + operationId: routeId, + surface, }); const componentOf = ( @@ -748,7 +784,8 @@ const prepareRender = async ( ): Promise => { const resolved = await resolveTarget(target, options); const renderer = await loadRenderer(); - const invocation = invocationFor(resolved.kind, resolved.provenance.routeId, options, resolved.provenance); + const surface = executableSurface(resolved.kind, resolved.provenance.routeId, resolved.manifest); + const invocation = invocationFor(resolved.kind, resolved.provenance.routeId, surface, options, resolved.provenance); const collected: AgentProgressUpdate[] = []; const context = options.context ?? {}; const signal = options.signal ?? new AbortController().signal; @@ -773,7 +810,7 @@ const prepareRender = async ( signal: request.signal, }), invocation: { - ...requestInvocation(request.invocation, resolved.provenance.routeId), + ...requestInvocation(request.invocation, resolved.provenance.routeId, surface), ...context.invocation, kind: request.invocation.kind, }, diff --git a/packages/agent-bundle/tests/projection/providers.test.ts b/packages/agent-bundle/tests/projection/providers.test.ts index 2a5a8a040..9540e29b0 100644 --- a/packages/agent-bundle/tests/projection/providers.test.ts +++ b/packages/agent-bundle/tests/projection/providers.test.ts @@ -79,13 +79,24 @@ describe('conventional providers through the harness', () => { }); }); - it('mounts providers for a rendered script with the script invocation', async () => { + it('mounts providers for a rendered script with the script name the generated script passes', async () => { const rendered = await renderRoute('script:tooling-summary', { args: ['--fast', 'a.mp4'] }); + // The generated script passes `name: 'tooling-summary'`, never the route id. expect(rendered.result).toEqual({ arguments: 2, keys: ['libraryTooling', 'processLifetime'], - libraryTooling: { kind: 'script', surface: 'script:tooling-summary', tool: 'ffprobe 6.1' }, + libraryTooling: { kind: 'script', surface: 'tooling-summary', tool: 'ffprobe 6.1' }, + }); + }); + + it('mounts providers for a rendered CLI route at the route-unit level with the command path', async () => { + const rendered = await renderRoute('cli:tooling/report'); + + // The generated executable passes `command.path.join(' ')`, never the route id. + expect(rendered.result).toEqual({ + keys: ['libraryTooling', 'processLifetime'], + libraryTooling: { kind: 'cli', surface: 'tooling report', tool: 'ffprobe 6.1' }, }); }); From c54dc98aec6a006f1ebdf28894499c9d46c5ded5 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 07:18:46 +0000 Subject: [PATCH 06/13] fix(test): pin the tooling tool in the packed projection and ignore example artifacts The packed stdio projection lists the route-harness tools, which now include `tooling`. Every example's build writes `examples//artifact/`; the previous commit accidentally tracked three of them, so ignore the whole family and untrack the accidental copies. --- .gitignore | 4 +- .../artifact/agent-bundle.hooks.json | 1 - .../artifact/agent-bundle.manifest.json | 1 - .../claude/.claude-plugin/marketplace.json | 1 - .../claude/.claude-plugin/plugin.json | 1 - .../artifact/claude/INSTALL.md | 18 - .../assets/release/release-manifest.json | 21 - .../claude/assets/release/risk-register.json | 16 - .../artifact/claude/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 251 - .../claude/scripts/verify-release.mjs | 54 - .../codex/.agents/plugins/marketplace.json | 1 - .../artifact/codex/.codex-plugin/plugin.json | 1 - .../artifact/codex/INSTALL.md | 16 - .../assets/release/release-manifest.json | 21 - .../codex/assets/release/risk-register.json | 16 - .../artifact/codex/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 254 - .../artifact/codex/scripts/verify-release.mjs | 54 - .../artifact/portable/INSTALL.md | 19 - .../assets/release/release-manifest.json | 21 - .../assets/release/risk-register.json | 16 - .../artifact/portable/install.mjs | 80 - .../artifact/portable/plugin.json | 1 - .../artifact/portable/scripts/detect-risk.mjs | 35 - .../portable/scripts/verify-release.mjs | 54 - .../mcp-app/artifact/agent-bundle.hooks.json | 1 - .../artifact/agent-bundle.manifest.json | 1 - .../claude/.claude-plugin/marketplace.json | 1 - .../claude/.claude-plugin/plugin.json | 1 - examples/mcp-app/artifact/claude/.mcp.json | 1 - examples/mcp-app/artifact/claude/INSTALL.md | 18 - .../assets/evals/fixtures/status/result.json | 9 - .../mcp-app/artifact/claude/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 251 - .../claude/mcp/mcp-status-073c1634.mjs | 30761 --------------- .../claude/scripts/check-service-fixture.mjs | 60 - .../claude/skills/service-readiness/SKILL.md | 33 - .../assets/readiness-report.md | 22 - .../references/status-policy.md | 22 - .../codex/.agents/plugins/marketplace.json | 1 - .../artifact/codex/.codex-plugin/plugin.json | 1 - examples/mcp-app/artifact/codex/.mcp.json | 1 - examples/mcp-app/artifact/codex/INSTALL.md | 16 - .../assets/evals/fixtures/status/result.json | 9 - .../mcp-app/artifact/codex/hooks/hooks.json | 1 - .../session-start-session-start-7ab7e8a5.mjs | 254 - .../codex/mcp/mcp-status-073c1634.mjs | 30761 --------------- .../codex/scripts/check-service-fixture.mjs | 60 - .../codex/skills/service-readiness/SKILL.md | 33 - .../assets/readiness-report.md | 22 - .../references/status-policy.md | 22 - examples/mcp-app/artifact/portable/INSTALL.md | 19 - .../assets/evals/fixtures/status/result.json | 9 - .../mcp-app/artifact/portable/install.mjs | 80 - .../artifact/portable/mcp-apps/status.html | 154 - examples/mcp-app/artifact/portable/mcp.json | 1 - .../portable/mcp/mcp-status-073c1634.mjs | 30768 ---------------- .../mcp-app/artifact/portable/plugin.json | 1 - .../scripts/check-service-fixture.mjs | 60 - .../skills/service-readiness/SKILL.md | 33 - .../assets/readiness-report.md | 22 - .../references/status-policy.md | 22 - .../artifact/agent-bundle.hooks.json | 1 - .../artifact/agent-bundle.manifest.json | 1 - .../claude/.claude-plugin/marketplace.json | 1 - .../claude/.claude-plugin/plugin.json | 1 - .../skills-starter/artifact/claude/INSTALL.md | 18 - .../claude/skills/dependency-upgrade/SKILL.md | 33 - .../dependency-upgrade/assets/upgrade-plan.md | 21 - .../references/compatibility-checklist.md | 9 - .../claude/skills/incident-triage/SKILL.md | 34 - .../incident-triage/assets/incident-update.md | 9 - .../references/triage-runbook.md | 9 - .../claude/skills/release-review/SKILL.md | 34 - .../release-review/assets/report-template.md | 22 - .../release-review/references/checklist.md | 8 - .../references/release-policy.md | 22 - .../codex/.agents/plugins/marketplace.json | 1 - .../artifact/codex/.codex-plugin/plugin.json | 1 - .../skills-starter/artifact/codex/INSTALL.md | 16 - .../codex/skills/dependency-upgrade/SKILL.md | 33 - .../dependency-upgrade/assets/upgrade-plan.md | 21 - .../references/compatibility-checklist.md | 9 - .../codex/skills/incident-triage/SKILL.md | 34 - .../incident-triage/assets/incident-update.md | 9 - .../references/triage-runbook.md | 9 - .../codex/skills/release-review/SKILL.md | 34 - .../release-review/assets/report-template.md | 22 - .../release-review/references/checklist.md | 8 - .../references/release-policy.md | 22 - .../artifact/portable/INSTALL.md | 19 - .../artifact/portable/install.mjs | 80 - .../artifact/portable/plugin.json | 1 - .../skills/dependency-upgrade/SKILL.md | 33 - .../dependency-upgrade/assets/upgrade-plan.md | 21 - .../references/compatibility-checklist.md | 9 - .../portable/skills/incident-triage/SKILL.md | 34 - .../incident-triage/assets/incident-update.md | 9 - .../references/triage-runbook.md | 9 - .../portable/skills/release-review/SKILL.md | 34 - .../release-review/assets/report-template.md | 22 - .../release-review/references/checklist.md | 8 - .../references/release-policy.md | 22 - .../tests/packed-stdio-projection.test.ts | 1 + 105 files changed, 3 insertions(+), 95232 deletions(-) delete mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.hooks.json delete mode 100644 examples/hooks-and-scripts/artifact/agent-bundle.manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/INSTALL.md delete mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/hooks.json delete mode 100644 examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs delete mode 100644 examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/INSTALL.md delete mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/hooks.json delete mode 100644 examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs delete mode 100644 examples/hooks-and-scripts/artifact/portable/INSTALL.md delete mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json delete mode 100644 examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json delete mode 100644 examples/hooks-and-scripts/artifact/portable/install.mjs delete mode 100644 examples/hooks-and-scripts/artifact/portable/plugin.json delete mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs delete mode 100644 examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs delete mode 100644 examples/mcp-app/artifact/agent-bundle.hooks.json delete mode 100644 examples/mcp-app/artifact/agent-bundle.manifest.json delete mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json delete mode 100644 examples/mcp-app/artifact/claude/.claude-plugin/plugin.json delete mode 100644 examples/mcp-app/artifact/claude/.mcp.json delete mode 100644 examples/mcp-app/artifact/claude/INSTALL.md delete mode 100644 examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json delete mode 100644 examples/mcp-app/artifact/claude/hooks/hooks.json delete mode 100644 examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs delete mode 100644 examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs delete mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md delete mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md delete mode 100644 examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md delete mode 100644 examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json delete mode 100644 examples/mcp-app/artifact/codex/.codex-plugin/plugin.json delete mode 100644 examples/mcp-app/artifact/codex/.mcp.json delete mode 100644 examples/mcp-app/artifact/codex/INSTALL.md delete mode 100644 examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json delete mode 100644 examples/mcp-app/artifact/codex/hooks/hooks.json delete mode 100644 examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs delete mode 100644 examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs delete mode 100644 examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs delete mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md delete mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md delete mode 100644 examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md delete mode 100644 examples/mcp-app/artifact/portable/INSTALL.md delete mode 100644 examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json delete mode 100644 examples/mcp-app/artifact/portable/install.mjs delete mode 100644 examples/mcp-app/artifact/portable/mcp-apps/status.html delete mode 100644 examples/mcp-app/artifact/portable/mcp.json delete mode 100644 examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs delete mode 100644 examples/mcp-app/artifact/portable/plugin.json delete mode 100644 examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs delete mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md delete mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md delete mode 100644 examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md delete mode 100644 examples/skills-starter/artifact/agent-bundle.hooks.json delete mode 100644 examples/skills-starter/artifact/agent-bundle.manifest.json delete mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json delete mode 100644 examples/skills-starter/artifact/claude/.claude-plugin/plugin.json delete mode 100644 examples/skills-starter/artifact/claude/INSTALL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md delete mode 100644 examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md delete mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md delete mode 100644 examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/SKILL.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md delete mode 100644 examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md delete mode 100644 examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json delete mode 100644 examples/skills-starter/artifact/codex/.codex-plugin/plugin.json delete mode 100644 examples/skills-starter/artifact/codex/INSTALL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md delete mode 100644 examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md delete mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md delete mode 100644 examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/SKILL.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md delete mode 100644 examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md delete mode 100644 examples/skills-starter/artifact/portable/INSTALL.md delete mode 100644 examples/skills-starter/artifact/portable/install.mjs delete mode 100644 examples/skills-starter/artifact/portable/plugin.json delete mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md delete mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md delete mode 100644 examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md delete mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md delete mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md delete mode 100644 examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/SKILL.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md delete mode 100644 examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md diff --git a/.gitignore b/.gitignore index 7a5cb2ac5..7d6d8ee5a 100644 --- a/.gitignore +++ b/.gitignore @@ -5,8 +5,8 @@ dist/ coverage/ artifacts/ *.log -examples/audiobook-curator/artifact/ -examples/worktree-proximity/artifact/ +# Every example's `pnpm build` (and `pnpm examples:check`) writes here. +examples/*/artifact/ # Build-time copies of the root LICENSE and NOTICE (scripts/sync-license-files.mjs) packages/*/LICENSE diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json b/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json deleted file mode 100644 index c41cd4504..000000000 --- a/examples/hooks-and-scripts/artifact/agent-bundle.hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json b/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json deleted file mode 100644 index 631297a39..000000000 --- a/examples/hooks-and-scripts/artifact/agent-bundle.manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":287,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"f4dff087eb3c84f2b6e4ffeb632a3df21a631b70ad0328811dbaeabd8e29c043","sourceInputs":["agent-bundle.config.ts"]},{"bytes":182,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"2fa2d83fbdca7ab515bbd11c1cc2dffafedeabc2dc9cd647fb9646c057b31d54","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"claude/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"claude/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":11992,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"2faef48e3de116eea8e58c6e0d7f6cbfe4a98726fdcd6cc94f3ec5c5234c08ed","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":442,"kind":"generated","path":"claude/INSTALL.md","sha256":"0ca977cebb541b89cb7ef9cc47ed66dde2617f8c2beb5a697740ebfc2e4e0a14","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2089,"kind":"bundle","path":"claude/scripts/verify-release.mjs","sha256":"a9c836d6c1d878fd561788d2e6dab944f494e2aad25de0514a877246f1ba0854","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":264,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"eef1222beca7c354075e8da61d0fc50d68180b87da4f884890886868b6b40b89","sourceInputs":["agent-bundle.config.ts"]},{"bytes":534,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"e20e3a461fe89d8148d1aa53e729605316a6770215f86ec01c08ce7eaa672708","sourceInputs":["agent-bundle.config.ts"]},{"bytes":412,"kind":"copy","path":"codex/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"codex/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12115,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"f786240293d08a5f3b8c7c3778b67acd5b03a39fbd753c1ef56e30007b416838","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":330,"kind":"generated","path":"codex/INSTALL.md","sha256":"b36d9e71a3d9e39947164524196269ba4084a28f6595558548d5f2639fb171ef","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2089,"kind":"bundle","path":"codex/scripts/verify-release.mjs","sha256":"a9c836d6c1d878fd561788d2e6dab944f494e2aad25de0514a877246f1ba0854","sourceInputs":["src/scripts/verify-release.ts"]},{"bytes":412,"kind":"copy","path":"portable/assets/release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77","sourceInputs":["release/release-manifest.json"]},{"bytes":370,"kind":"copy","path":"portable/assets/release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb","sourceInputs":["release/risk-register.json"]},{"bytes":667,"kind":"generated","path":"portable/INSTALL.md","sha256":"9fca655cfae6999fdac7a6562b003dff2353231f936b65791c7859cf7437b5b1","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3311,"kind":"generated","path":"portable/install.mjs","sha256":"3d5bab7f4f63582ed41027cbdd58122cf8aa04436647400639876c264751447f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":186,"kind":"generated","path":"portable/plugin.json","sha256":"7960fb9bcfd13c8bfbf113ac8b742d45f341df6fedf1c91525c421b10f63ad1e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1446,"kind":"bundle","path":"portable/scripts/detect-risk.mjs","sha256":"4d6fcf62f9bca98dd46b02628a745df3a38438aa03039b61758722762e3e691e","sourceInputs":["agent-bundle.config.ts","src/scripts/detect-risk.ts"]},{"bytes":2089,"kind":"bundle","path":"portable/scripts/verify-release.mjs","sha256":"a9c836d6c1d878fd561788d2e6dab944f494e2aad25de0514a877246f1ba0854","sourceInputs":["src/scripts/verify-release.ts"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c","configPath":"agent-bundle.config.ts","modelDigest":"c9c2a9a138a4736257fd35f0108d5b702cfd532efee090e77c33bb6b91028b5e","packageName":"@agent-bundle-example/hooks-and-scripts","revision":"5ad60dd354b14a6236614519d6c0880685cfa4878580de76228b0042ac0d036d","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"a6b714ebca4e4c048fe437312e4789b0841dccfd8a621cfe513e6a0ae3fc7a4c"},{"executable":false,"path":"package.json","sha256":"f34dac2a9133c3775239a0df45afc301bb257f3e628551ac6c12aad787841af6"},{"executable":false,"path":"README.md","sha256":"a22188781290ce67939e8dd339bc75b6dd520ded36a02de0b8a161d3a776afa1"},{"executable":false,"path":"release/release-manifest.json","sha256":"5f40663b01a3b359b3df7d5d7f7fbd0b1f703adb4a3b6a55e57dc2bf6d9bfc77"},{"executable":false,"path":"release/risk-register.json","sha256":"aac96ec9112addc32a97c0f35fbda32d8f8104a321f1c2f4d97e10cbed25f0fb"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"a5cda975fd148cf904b3c0cc5b0a860061ed89acd3704d54427c1313f23668e8"},{"executable":false,"path":"src/scripts/detect-risk.ts","sha256":"3b1d88c26219a410b6b23c019632fa8330ba5421d9294abbe9fc3f5300720370"},{"executable":false,"path":"src/scripts/verify-release.ts","sha256":"af661a44e63f38726d237df8821426884f64386f1e0a9f5c8c369932eac341c3"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.7.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"1d43c5ed19de401fb7455c5912e4c21113f6e387aef4c28d2eca121f7554c4e8"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"986bcafa6ef46f9dc4558f05781f53400b3d75533a075068184ba8d43670d4ec"}]},{"adapterRevision":"1.5.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json deleted file mode 100644 index 2cae8a879..000000000 --- a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts-marketplace","owner":{"name":"hooks-and-scripts"},"plugins":[{"description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","source":"./","version":"1.0.0"}]} diff --git a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json b/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json deleted file mode 100644 index 38dc8d3b1..000000000 --- a/examples/hooks-and-scripts/artifact/claude/.claude-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/claude/INSTALL.md b/examples/hooks-and-scripts/artifact/claude/INSTALL.md deleted file mode 100644 index ea76a1f93..000000000 --- a/examples/hooks-and-scripts/artifact/claude/INSTALL.md +++ /dev/null @@ -1,18 +0,0 @@ -# Install hooks-and-scripts - -Hook simulation, script traces, logs, and recovery. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Claude Code - -Claude Code installs this bundle through its local marketplace contract: - -```sh -claude plugin marketplace add ./ -claude plugin install hooks-and-scripts@hooks-and-scripts-marketplace --scope user -``` - -Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json deleted file mode 100644 index 819d86560..000000000 --- a/examples/hooks-and-scripts/artifact/claude/assets/release/release-manifest.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "version": "2.4.0", - "changelog": "CHANGELOG.md#2.4.0", - "artifacts": [ - { - "name": "package", - "path": "dist/agent-bundle-2.4.0.tgz", - "status": "ready" - }, - { - "name": "checksums", - "path": "dist/agent-bundle-2.4.0.sha256", - "status": "ready" - }, - { - "name": "sbom", - "path": "dist/agent-bundle-2.4.0.sbom.json", - "status": "ready" - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json deleted file mode 100644 index 2295bcc45..000000000 --- a/examples/hooks-and-scripts/artifact/claude/assets/release/risk-register.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "risks": [ - { - "id": "REL-204", - "severity": "high", - "status": "open", - "summary": "Complete the final approval for the release notes before publishing." - }, - { - "id": "REL-198", - "severity": "medium", - "status": "mitigated", - "summary": "Package signing rehearsal is documented in the release runbook." - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json b/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json deleted file mode 100644 index 1afdaac5a..000000000 --- a/examples/hooks-and-scripts/artifact/claude/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index afc422ebd..000000000 --- a/examples/hooks-and-scripts/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,251 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, - `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, - 'Run detect-risk to surface open high-severity release blockers before publishing.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "claude"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeClaudeNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeClaudeNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeClaudeNative; -const encodeNative = encodeClaudeNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && 0) {} - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { - hookSpecificOutput: { - additionalContext: result.additionalContext, - hookEventName: nativeEvent - } - }; - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ - additionalContext: nativeOutput.hookSpecificOutput.additionalContext, - outcome: "continue" - }); - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (false) {} - else requireString(input, "transcript_path"); - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (false) {} - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (false) {} - else requireString(input, "last_assistant_message"); -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs deleted file mode 100644 index 576751775..000000000 --- a/examples/hooks-and-scripts/artifact/claude/scripts/verify-release.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const requiredArtifacts = [ - 'package', - 'checksums', - 'sbom' -]; -const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); -const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); -const validationErrors = (manifest)=>{ - const errors = []; - if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { - errors.push('version must use major.minor.patch format'); - } - if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { - errors.push('changelog must identify the release notes'); - } - for (const name of requiredArtifacts){ - const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); - if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { - errors.push(`${name} artifact must have a ready path`); - } - } - return errors; -}; -const main = async ()=>{ - try { - const manifest = await readManifest(); - const errors = validationErrors(manifest); - if (errors.length > 0) { - process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); - return 1; - } - process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const verify_release_entry_main = main; -if (typeof verify_release_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/verify-release.ts"); -} -const code = await verify_release_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json b/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json deleted file mode 100644 index 16e053eae..000000000 --- a/examples/hooks-and-scripts/artifact/codex/.agents/plugins/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"interface":{"displayName":"hooks-and-scripts"},"name":"hooks-and-scripts-marketplace","plugins":[{"category":"Productivity","name":"hooks-and-scripts","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json b/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json deleted file mode 100644 index eeee06783..000000000 --- a/examples/hooks-and-scripts/artifact/codex/.codex-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"hooks-and-scripts"},"description":"Hook simulation, script traces, logs, and recovery.","hooks":"./hooks/hooks.json","interface":{"capabilities":["hooks"],"category":"Productivity","defaultPrompt":["Help me use hooks-and-scripts."],"developerName":"hooks-and-scripts","displayName":"hooks-and-scripts","longDescription":"Hook simulation, script traces, logs, and recovery.","shortDescription":"Hook simulation, script traces, logs, and recovery."},"name":"hooks-and-scripts","skills":"./skills/","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/codex/INSTALL.md b/examples/hooks-and-scripts/artifact/codex/INSTALL.md deleted file mode 100644 index 97ee12563..000000000 --- a/examples/hooks-and-scripts/artifact/codex/INSTALL.md +++ /dev/null @@ -1,16 +0,0 @@ -# Install hooks-and-scripts - -Hook simulation, script traces, logs, and recovery. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Codex - -Codex installs this bundle from its local marketplace snapshot: - -```sh -codex plugin marketplace add ./ -codex plugin add hooks-and-scripts@hooks-and-scripts-marketplace -``` diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json deleted file mode 100644 index 819d86560..000000000 --- a/examples/hooks-and-scripts/artifact/codex/assets/release/release-manifest.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "version": "2.4.0", - "changelog": "CHANGELOG.md#2.4.0", - "artifacts": [ - { - "name": "package", - "path": "dist/agent-bundle-2.4.0.tgz", - "status": "ready" - }, - { - "name": "checksums", - "path": "dist/agent-bundle-2.4.0.sha256", - "status": "ready" - }, - { - "name": "sbom", - "path": "dist/agent-bundle-2.4.0.sbom.json", - "status": "ready" - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json deleted file mode 100644 index 2295bcc45..000000000 --- a/examples/hooks-and-scripts/artifact/codex/assets/release/risk-register.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "risks": [ - { - "id": "REL-204", - "severity": "high", - "status": "open", - "summary": "Complete the final approval for the release notes before publishing." - }, - { - "id": "REL-198", - "severity": "medium", - "status": "mitigated", - "summary": "Package signing rehearsal is documented in the release runbook." - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json b/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json deleted file mode 100644 index eb4f61756..000000000 --- a/examples/hooks-and-scripts/artifact/codex/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index ba527da9c..000000000 --- a/examples/hooks-and-scripts/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,254 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `This release preparation session is active for ${event.sessionId ?? 'this session'} from ${event.source ?? 'an unknown source'}.`, - `Run verify-release from ${event.cwd ?? process.cwd()} to confirm the manifest is ready for packaging.`, - 'Run detect-risk to surface open high-severity release blockers before publishing.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "codex"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeCodexNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeCodexNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeCodexNative; -const encodeNative = encodeCodexNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (true) requireNullableString(input, "transcript_path"); - else {} - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (true) { - requireString(input, "turn_id"); - requireString(input, "model"); - requireString(input, "permission_mode"); - if (![ - "default", - "acceptEdits", - "plan", - "dontAsk", - "bypassPermissions" - ].includes(input.permission_mode)) fail("native permission_mode is invalid"); - } - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (true) requireNullableString(input, "last_assistant_message"); - else {} -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs deleted file mode 100644 index 576751775..000000000 --- a/examples/hooks-and-scripts/artifact/codex/scripts/verify-release.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const requiredArtifacts = [ - 'package', - 'checksums', - 'sbom' -]; -const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); -const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); -const validationErrors = (manifest)=>{ - const errors = []; - if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { - errors.push('version must use major.minor.patch format'); - } - if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { - errors.push('changelog must identify the release notes'); - } - for (const name of requiredArtifacts){ - const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); - if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { - errors.push(`${name} artifact must have a ready path`); - } - } - return errors; -}; -const main = async ()=>{ - try { - const manifest = await readManifest(); - const errors = validationErrors(manifest); - if (errors.length > 0) { - process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); - return 1; - } - process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const verify_release_entry_main = main; -if (typeof verify_release_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/verify-release.ts"); -} -const code = await verify_release_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/INSTALL.md b/examples/hooks-and-scripts/artifact/portable/INSTALL.md deleted file mode 100644 index 0c3c03165..000000000 --- a/examples/hooks-and-scripts/artifact/portable/INSTALL.md +++ /dev/null @@ -1,19 +0,0 @@ -# Install hooks-and-scripts - -Hook simulation, script traces, logs, and recovery. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Portable Agent Plugin - -Portable is a distribution profile, not a host runtime with one universal install location. -This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). -Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run -`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT -are also native clients. The bundled installer provides the Cursor local copy: - -```sh -node ./install.mjs -``` diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json b/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json deleted file mode 100644 index 819d86560..000000000 --- a/examples/hooks-and-scripts/artifact/portable/assets/release/release-manifest.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "version": "2.4.0", - "changelog": "CHANGELOG.md#2.4.0", - "artifacts": [ - { - "name": "package", - "path": "dist/agent-bundle-2.4.0.tgz", - "status": "ready" - }, - { - "name": "checksums", - "path": "dist/agent-bundle-2.4.0.sha256", - "status": "ready" - }, - { - "name": "sbom", - "path": "dist/agent-bundle-2.4.0.sbom.json", - "status": "ready" - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json b/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json deleted file mode 100644 index 2295bcc45..000000000 --- a/examples/hooks-and-scripts/artifact/portable/assets/release/risk-register.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "risks": [ - { - "id": "REL-204", - "severity": "high", - "status": "open", - "summary": "Complete the final approval for the release notes before publishing." - }, - { - "id": "REL-198", - "severity": "medium", - "status": "mitigated", - "summary": "Package signing rehearsal is documented in the release runbook." - } - ] -} diff --git a/examples/hooks-and-scripts/artifact/portable/install.mjs b/examples/hooks-and-scripts/artifact/portable/install.mjs deleted file mode 100644 index 8873d4b6a..000000000 --- a/examples/hooks-and-scripts/artifact/portable/install.mjs +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node -import { createHash } from 'node:crypto'; -import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const pluginName = "hooks-and-scripts"; -const pluginVersion = "1.0.0"; -const source = resolve(fileURLToPath(new URL('.', import.meta.url))); -const cursorRoot = join(homedir(), '.cursor'); -const installRoot = join(cursorRoot, 'plugins', 'local'); -const destination = join(installRoot, pluginName); - -const exists = async (path) => { - try { await lstat(path); return true; } - catch (error) { if (error?.code === 'ENOENT') return false; throw error; } -}; - -const treeHash = async (root, prefix = '') => { - const rootMetadata = await lstat(root); - if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { - throw new Error('Refusing unsupported filesystem entry ".".'); - } - const hash = createHash('sha256'); - const visit = async (relative) => { - const absolute = join(root, relative); - const metadata = await lstat(absolute); - if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { - throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); - } - if (metadata.isDirectory()) { - for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); - return; - } - hash.update(relative.replaceAll('\\', '/')); - hash.update('\0'); - hash.update(await readFile(absolute)); - hash.update('\0'); - }; - for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); - return hash.digest('hex'); -}; - -const installedVersion = async () => { - for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { - try { - const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); - if (typeof value.version === 'string') return value.version; - } catch (error) { if (error?.code !== 'ENOENT') throw error; } - } - return undefined; -}; - -if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { - throw new Error(`Cursor is not installed in ${cursorRoot}.`); -} -await mkdir(installRoot, { recursive: true }); -if (await exists(destination)) { - const currentVersion = await installedVersion(); - if (currentVersion !== undefined && currentVersion !== pluginVersion) { - throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); - } - if (source === destination || await treeHash(source) === await treeHash(destination)) { - console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); - process.exit(0); - } - throw new Error(`Refusing content collision at ${destination}.`); -} - -const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); -const stage = join(stageParent, 'bundle'); -try { - await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); - await treeHash(stage); - await rename(stage, destination); - console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); -} finally { - await rm(stageParent, { force: true, recursive: true }); -} diff --git a/examples/hooks-and-scripts/artifact/portable/plugin.json b/examples/hooks-and-scripts/artifact/portable/plugin.json deleted file mode 100644 index 2f19512e9..000000000 --- a/examples/hooks-and-scripts/artifact/portable/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"Hook simulation, script traces, logs, and recovery.","name":"hooks-and-scripts","version":"1.0.0"} diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs deleted file mode 100644 index 6d3a3e5fe..000000000 --- a/examples/hooks-and-scripts/artifact/portable/scripts/detect-risk.mjs +++ /dev/null @@ -1,35 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const registerPath = new URL('../assets/release/risk-register.json', import.meta.url); -const main = async ()=>{ - try { - const register = JSON.parse(await readFile(registerPath, 'utf8')); - if (!Array.isArray(register.risks)) throw new Error('risk register must contain a risks array'); - const blockers = register.risks.filter((risk)=>risk.status === 'open' && risk.severity === 'high'); - if (blockers.length === 0) { - process.stdout.write('No open high-severity release risks found.\n'); - return 0; - } - for (const risk of blockers){ - process.stderr.write(`${typeof risk.id === 'string' ? risk.id : 'UNIDENTIFIED'}: ${typeof risk.summary === 'string' ? risk.summary : 'Open high-severity release risk'}\n`); - } - return 2; - } catch (error) { - process.stderr.write(`Unable to detect release risks: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const detect_risk_entry_main = main; -if (typeof detect_risk_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/detect-risk.ts"); -} -const code = await detect_risk_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs b/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs deleted file mode 100644 index 576751775..000000000 --- a/examples/hooks-and-scripts/artifact/portable/scripts/verify-release.mjs +++ /dev/null @@ -1,54 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - - -const requiredArtifacts = [ - 'package', - 'checksums', - 'sbom' -]; -const manifestPath = new URL('../assets/release/release-manifest.json', import.meta.url); -const readManifest = async ()=>JSON.parse(await readFile(manifestPath, 'utf8')); -const validationErrors = (manifest)=>{ - const errors = []; - if (typeof manifest.version !== 'string' || !/^\d+\.\d+\.\d+$/.test(manifest.version)) { - errors.push('version must use major.minor.patch format'); - } - if (typeof manifest.changelog !== 'string' || manifest.changelog.trim().length === 0) { - errors.push('changelog must identify the release notes'); - } - for (const name of requiredArtifacts){ - const artifact = manifest.artifacts?.find((candidate)=>candidate.name === name); - if (artifact === undefined || typeof artifact.path !== 'string' || artifact.path.trim().length === 0 || artifact.status !== 'ready') { - errors.push(`${name} artifact must have a ready path`); - } - } - return errors; -}; -const main = async ()=>{ - try { - const manifest = await readManifest(); - const errors = validationErrors(manifest); - if (errors.length > 0) { - process.stderr.write(`Release manifest is incomplete:\n${errors.map((error)=>`- ${error}`).join('\n')}\n`); - return 1; - } - process.stdout.write(`Release ${manifest.version} is ready for packaging.\n`); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify release manifest: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const verify_release_entry_main = main; -if (typeof verify_release_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/hooks-and-scripts/src/scripts/verify-release.ts"); -} -const code = await verify_release_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/agent-bundle.hooks.json b/examples/mcp-app/artifact/agent-bundle.hooks.json deleted file mode 100644 index c41cd4504..000000000 --- a/examples/mcp-app/artifact/agent-bundle.hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":[{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","target":"claude"},{"event":"sessionStart","id":"hook:session-start:session-start:7ab7e8a5","name":"session-start-session-start-7ab7e8a5","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","target":"codex"}]} diff --git a/examples/mcp-app/artifact/agent-bundle.manifest.json b/examples/mcp-app/artifact/agent-bundle.manifest.json deleted file mode 100644 index 02714aba2..000000000 --- a/examples/mcp-app/artifact/agent-bundle.manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":412,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"c085b5d4bc728917cba2d53546cdd9f6b065f9e84a846d31d3e4ccb254f5819a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":353,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"e4cf51c12ad7b9c9c78c3ae09e1564bff251152d162cd562247e8f5dca5868a7","sourceInputs":["agent-bundle.config.ts"]},{"bytes":214,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"20bca77e21ea7fbb9ceb1c1fd0c06b7bd67216a20d8a9922fab5ad8f915e5604","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":180,"kind":"generated","path":"claude/.mcp.json","sha256":"f7d402486d6d2de1fbbf6d95183a7f16aaed23f1b4b625c4075e3a67d11458aa","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"claude/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":150,"kind":"generated","path":"claude/hooks/hooks.json","sha256":"8855c477158d687920a5d1da416ee8c980cc305f3adde65488dcef55e8b8da06","sourceInputs":["agent-bundle.config.ts"]},{"bytes":11989,"kind":"bundle","path":"claude/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"8928c1304415af7a31d6462ce1fafb9ff6139bd6555b561b84759148589e23ba","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":472,"kind":"generated","path":"claude/INSTALL.md","sha256":"84f35da9c85137d58c7ea6e458c1794e3396d95e709a2dde0784014ca784bb1b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"claude/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2331,"kind":"bundle","path":"claude/scripts/check-service-fixture.mjs","sha256":"16cf8a97c4e57bca609029a008621e944ac122a0760180d246d415495feee8a0","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"claude/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"claude/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"claude/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":258,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"c8b0fe73ece00cbf09fed92e1011d2d5e28211c7e7f4dfa1fddf3fba4c462b0a","sourceInputs":["agent-bundle.config.ts"]},{"bytes":674,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"8dd1d6259f076f8f62cd35bb7c466c3dec95aeb4433416f4e52202f56673c11e","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts","src/skills/service-readiness/SKILL.md"]},{"bytes":152,"kind":"generated","path":"codex/.mcp.json","sha256":"62064b39f8cddd0db51b7aa25a688bbff3ae7621376be506ff5d5542b037c9de","sourceInputs":["agent-bundle.config.ts","src/mcp/status.ts"]},{"bytes":231,"kind":"copy","path":"codex/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":143,"kind":"generated","path":"codex/hooks/hooks.json","sha256":"ad0e296b15c799f52459488b17f46f7cc3a34e1abf4b9466a178d17a7fdaa605","sourceInputs":["agent-bundle.config.ts"]},{"bytes":12112,"kind":"bundle","path":"codex/hooks/session-start-session-start-7ab7e8a5.mjs","sha256":"850177a3fd7d801a7ffeb69ea0b936cad3b0fe939d8db84438b39d22353d0442","sourceInputs":["agent-bundle.config.ts","src/hooks/session-start.ts"]},{"bytes":360,"kind":"generated","path":"codex/INSTALL.md","sha256":"4efefa497a9acdd073703dfc3ff2c81cd5005cea0f777a204a275988193c907f","sourceInputs":["agent-bundle.config.ts"]},{"bytes":1211760,"kind":"bundle","path":"codex/mcp/mcp-status-073c1634.mjs","sha256":"80aa4516620d80e170e0ead5efcf49b7ea910a9dd36fed2a0f8e7f9f3e52c406","sourceInputs":["src/compiler-status-contract.ts","src/mcp/status.ts"]},{"bytes":2331,"kind":"bundle","path":"codex/scripts/check-service-fixture.mjs","sha256":"16cf8a97c4e57bca609029a008621e944ac122a0760180d246d415495feee8a0","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"codex/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"codex/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"codex/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]},{"bytes":231,"kind":"copy","path":"portable/assets/evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811","sourceInputs":["evals/fixtures/status/result.json"]},{"bytes":701,"kind":"generated","path":"portable/INSTALL.md","sha256":"be9540f5b8012f6a7963532282469fa34119537a7203237fb18fd0b09f1710e3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3309,"kind":"generated","path":"portable/install.mjs","sha256":"971868b98246361915db7b21461b3cb105cc02bc0c163b70acaef9d89d0f9d6b","sourceInputs":["agent-bundle.config.ts"]},{"bytes":447791,"kind":"bundle","path":"portable/mcp-apps/status.html","sha256":"b201f81745e2b36afc11433bd6232e4ac4979b9759411c7794aaa69017f6345d","sourceInputs":["agent-bundle.config.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":242,"kind":"generated","path":"portable/mcp.json","sha256":"79461543b66617388e3ead6b60c90576ee9ed9be17d4e19e2febf58b872e05e3","sourceInputs":["src/mcp/status.ts"]},{"bytes":1674914,"kind":"bundle","path":"portable/mcp/mcp-status-073c1634.mjs","sha256":"7203edfea8a8186dd4e00f1d839d46d409fde1e2ff4ddd931c828dd4f98c4fec","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/mcp/status.ts","views/status-panel.html","views/status-panel.ts"]},{"bytes":220,"kind":"generated","path":"portable/plugin.json","sha256":"e0e8d291a995eece0fdaf1200e86cd06089c219f1c74cbc55241b89e93fa72f3","sourceInputs":["agent-bundle.config.ts"]},{"bytes":2331,"kind":"bundle","path":"portable/scripts/check-service-fixture.mjs","sha256":"16cf8a97c4e57bca609029a008621e944ac122a0760180d246d415495feee8a0","sourceInputs":["agent-bundle.config.ts","src/compiler-status-contract.ts","src/scripts/check-service-fixture.ts"]},{"bytes":528,"kind":"copy","path":"portable/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b","sourceInputs":["src/skills/service-readiness/assets/readiness-report.md","src/skills/service-readiness/SKILL.md"]},{"bytes":904,"kind":"copy","path":"portable/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b","sourceInputs":["src/skills/service-readiness/references/status-policy.md","src/skills/service-readiness/SKILL.md"]},{"bytes":1344,"kind":"copy","path":"portable/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3","sourceInputs":["src/skills/service-readiness/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89","configPath":"agent-bundle.config.ts","modelDigest":"8551c2c0a6630de6e3366155442b9919259fbf3331245219ad6e6dc4549069b3","packageName":"@agent-bundle-example/mcp-app","revision":"07e4db3dc80d12117f1d19af19e37d77502c9da1637f9f02e730ced76d634647","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"c6ec1f92b7f7f28c7eb485b9ad22b0fdda89ea63e58166a27b9969d0243cef89"},{"executable":false,"path":"evals/fixtures/status/result.json","sha256":"f9a03542d74a4f7e3ecac0ea161b820f0dcbbdfc4c1db3889401064653bd9811"},{"executable":false,"path":"evals/graders/status-result.ts","sha256":"b846dd661ff5f9af9dd15df7a2208344c13c6153514c9435a585a0caa820ebaf"},{"executable":false,"path":"evals/status.eval.ts","sha256":"ad0f9f1e216aec4684b4b51e337387b893c978e827ae8c5edf2ea41dfdf82207"},{"executable":false,"path":"package.json","sha256":"c98a8326ac7b5e0a0af64b14c59052387237354fc7c37c99d9de844ca07e3cbd"},{"executable":false,"path":"README.md","sha256":"35e3f3656ce34c5ed1181917ecebc40d10ec3f121630ade7ff7db7093e2db6df"},{"executable":false,"path":"rstest.browser-app.config.ts","sha256":"e2de9384badc7c4fb6b89ea5b54ed85fd3cacbe9e31162555362d0c89a318557"},{"executable":false,"path":"src/compiler-status-contract.ts","sha256":"ff8484b2ae613abb1cf2f76c70f558733563228570df1c05485a3a04ebffcd59"},{"executable":false,"path":"src/hooks/session-start.ts","sha256":"b856621ec280ed94a8e1dfa0fe065a1ff4d41690ff07be9e148c01b1180fd346"},{"executable":false,"path":"src/mcp/status.ts","sha256":"9116902d7041d30b4c3fcb412b2d83a793975fdac9632648e07dfc85da2a73c1"},{"executable":false,"path":"src/scripts/check-service-fixture.ts","sha256":"32967d447487049c62af2195612ec6f2b5de630753ea2c20b473faf93e804fba"},{"executable":false,"path":"src/skills/service-readiness/assets/readiness-report.md","sha256":"772e118b18070497c0f589bc4f9b37c71ade5ce59ba4a6904c65b2b724f8714b"},{"executable":false,"path":"src/skills/service-readiness/references/status-policy.md","sha256":"0319ad5884b291b01433d559429dcdb5d265bc5715b3c7bff734afa257ebef5b"},{"executable":false,"path":"src/skills/service-readiness/SKILL.md","sha256":"de9bebc358e0ba30d769d7e9bad6175251a858efe4e704941f9ef6dc830261f3"},{"executable":false,"path":"tests/browser-app/status-panel.browser.test.ts","sha256":"a49e632decebd56db42214afc3f1cba8729c24b594935e4b2468e3a2d4ad6695"},{"executable":false,"path":"views/status-panel.html","sha256":"75018093566d7bfdf16dfffcc072d4983e0c2ecd5f40f592e27e571cb3e5a868"},{"executable":false,"path":"views/status-panel.ts","sha256":"3bd3017d4f4d730293b15f386c5949b390bc8bba1ed2c5fd861efed477afefc8"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.7.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"1d43c5ed19de401fb7455c5912e4c21113f6e387aef4c28d2eca121f7554c4e8"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"986bcafa6ef46f9dc4558f05781f53400b3d75533a075068184ba8d43670d4ec"}]},{"adapterRevision":"1.5.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json b/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json deleted file mode 100644 index d24f68ca5..000000000 --- a/examples/mcp-app/artifact/claude/.claude-plugin/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example-marketplace","owner":{"name":"mcp-app-example"},"plugins":[{"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","source":"./","version":"1.0.0"}]} diff --git a/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json b/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json deleted file mode 100644 index 3a3e7a43d..000000000 --- a/examples/mcp-app/artifact/claude/.claude-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/claude/.mcp.json b/examples/mcp-app/artifact/claude/.mcp.json deleted file mode 100644 index a8c317b72..000000000 --- a/examples/mcp-app/artifact/claude/.mcp.json +++ /dev/null @@ -1 +0,0 @@ -{"mcpServers":{"status":{"args":["${CLAUDE_PLUGIN_ROOT}/mcp/mcp-status-073c1634.mjs"],"command":"node","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${CLAUDE_PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/claude/INSTALL.md b/examples/mcp-app/artifact/claude/INSTALL.md deleted file mode 100644 index b69cfdbf3..000000000 --- a/examples/mcp-app/artifact/claude/INSTALL.md +++ /dev/null @@ -1,18 +0,0 @@ -# Install mcp-app-example - -A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Claude Code - -Claude Code installs this bundle through its local marketplace contract: - -```sh -claude plugin marketplace add ./ -claude plugin install mcp-app-example@mcp-app-example-marketplace --scope user -``` - -Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json deleted file mode 100644 index a765aa4b5..000000000 --- a/examples/mcp-app/artifact/claude/assets/evals/fixtures/status/result.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "service": "compiler", - "status": "healthy", - "summary": "Compiler service is ready for release.", - "checks": [ - { "label": "Availability", "status": "passing" }, - { "label": "Build queue", "status": "passing" } - ] -} diff --git a/examples/mcp-app/artifact/claude/hooks/hooks.json b/examples/mcp-app/artifact/claude/hooks/hooks.json deleted file mode 100644 index 1afdaac5a..000000000 --- a/examples/mcp-app/artifact/claude/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${CLAUDE_PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index 4b76f8870..000000000 --- a/examples/mcp-app/artifact/claude/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,251 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, - `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, - 'Use show-status for compiler or payments-api when live service evidence is needed.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "claude"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeClaudeNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeClaudeNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeClaudeNative; -const encodeNative = encodeClaudeNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && 0) {} - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && result.additionalContext !== undefined) return { - hookSpecificOutput: { - additionalContext: result.additionalContext, - hookEventName: nativeEvent - } - }; - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && isRecord(nativeOutput.hookSpecificOutput)) return defined({ - additionalContext: nativeOutput.hookSpecificOutput.additionalContext, - outcome: "continue" - }); - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (false) {} - else requireString(input, "transcript_path"); - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (false) {} - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (false) {} - else requireString(input, "last_assistant_message"); -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs deleted file mode 100644 index 29189bf45..000000000 --- a/examples/mcp-app/artifact/claude/mcp/mcp-status-073c1634.mjs +++ /dev/null @@ -1,30761 +0,0 @@ -import node_process from "node:process"; - -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/mcp/status.ts -var status_namespaceObject = {}; -__webpack_require__.r(status_namespaceObject); -__webpack_require__.d(status_namespaceObject, { - createStatusServer: () => (createStatusServer), - "default": () => (mcp_status) }); - - -// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs -var stdio_namespaceObject = {}; -__webpack_require__.r(stdio_namespaceObject); -__webpack_require__.d(stdio_namespaceObject, { - StdioServerTransport: () => (stdio_StdioServerTransport) }); - - -//#region rolldown:runtime -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); -var __exportAll = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp(target, Symbol.toStringTag, { value: "Module" }); - } - return target; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { - key = keys[i]; - if (!__hasOwnProp.call(to, key) && key !== except) { - __defProp(to, key, { - get: ((k) => from[k]).bind(null, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - } - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { - value: mod, - enumerable: true -}) : target, mod)); - -//#endregion - -//#region ../core-internal/src/validators/dialects.ts -/** -* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). -*/ -const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); -const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); -const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); -const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); -/** -* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with -* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so -* wire-layer callers can consult it for documents whose dialect may be unsupported. -*/ -function declares2019Dialect($schema) { - return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); -} -/** -* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means -* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the -* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling -* provider's escape hatch in that message. -*/ -function declaredDialect(schema, remedy) { - if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; - const declared = schema.$schema.replace(/#$/, ""); - if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; - if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; - if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; - throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); -} - -//#endregion - -//# sourceMappingURL=dialects-DoSzNhcb.mjs.map - -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function toZod() { - return (schema) => schema; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function util_cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. - const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) - return 0; - return ratio - roundedRatio; -} -const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - // Circular reference detected, return undefined to break the cycle - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function util_esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function util_isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const util_allowsEval = /* @__PURE__*/ util_cached(() => { - // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. - if (globalConfig.jitless) { - return false; - } - // @ts-ignore - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (util_isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - // modified prototype - const prot = ctor.prototype; - if (util_isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - if (o instanceof Map) - return new Map(o); - if (o instanceof Set) - return new Set(o); - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - // @ts-ignore - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); -const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ - "string", - "number", - "bigint", - "boolean", - "symbol", - "undefined", -]))); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; - }); -} -// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. -const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}))(); -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - // `for...in` skips symbols, so a symbol in the mask would select nothing - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - assignProp(newShape, key, currDef.shape[key]); - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values - const existingShape = schema._zod.def.shape; - for (const key of Reflect.ownKeys(shape)) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function merge(a, b) { - if (!b?._zod?.def) { - throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); - } - if (a._zod.def.checks?.length) { - throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - } - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [], - }); - return clone(a, def); -} -function partial(Class, schema, mask, name = "partial") { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(`.${name}() cannot be used on object schemas containing refinements`); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - // the spread copies symbol keys; `for...in` would not reach them - for (const key of Reflect.ownKeys(oldShape)) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function util_required(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key of Reflect.ownKeys(oldShape)) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - }); - return clone(schema, def); -} -// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue === false) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ -function attachSchema(issues, start, inst) { - var _a; - for (let i = start; i < issues.length; i++) { - (_a = issues[i]).schema ?? (_a.schema = inst); - } -} -function finalizeIssue(iss, ctx, config) { - var _a; - // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. - const traits = iss.inst?._zod?.traits; - if (traits?.has("$ZodType")) { - if (traits.has("$ZodCheck")) - (_a = iss).schema ?? (_a.schema = iss.inst); - else - iss.schema = iss.inst; - } - // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. - const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; - const message = iss.message - ? iss.message - : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(schemaError?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"); - const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) { - rest.input = _input; - } - return rest; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - // @ts-ignore - if (input instanceof File) - return "file"; - return "unknown"; -} -const highSurrogate = /[\uD800-\uDBFF]/; -// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. -function codePointLength(str) { - const units = str.length; - if (!highSurrogate.test(str)) - return units; - let count = units; - for (let i = 0; i < units - 1; i++) { - if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - count--; - i++; - } - } - return count; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data) { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "nan" : "number"; - } - case "object": { - if (data === null) { - return "null"; - } - if (Array.isArray(data)) { - return "array"; - } - const obj = data; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// Codec utility functions -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -// instanceof -class util_Class { - constructor(..._args) { } -} -////////// PROTOTYPE INSTALLERS ////////// -// -// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. -/** - * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. - * - * Call this from a `proto` initializer, which runs once per prototype — never per instance. - */ -function util_members(proto, table) { - for (const key in table) { - const desc = Object.getOwnPropertyDescriptor(table, key); - // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was - if (desc.get) - Object.defineProperty(proto, key, { ...desc, enumerable: false }); - // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` - else - defineBound(proto, key, desc.value); - } -} -/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ -function util_own(inst, key, value, enumerable = true) { - Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); - return value; -} -/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ -function hide(inst, key, value) { - return util_own(inst, key, value, false); -} -function defineBound(proto, key, fn) { - Object.defineProperty(proto, key, { - configurable: true, - get() { - // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method - return this == null ? fn : util_own(this, key, fn.bind(this)); - }, - set(value) { - util_own(this, key, value); - }, - }); -} -/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ -function claim(inst, sentinel) { - const proto = Object.getPrototypeOf(inst); - // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. - return sentinel in proto ? undefined : proto; -} -// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. -let installing; -// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. -let broke = false; -const breaker = { - configurable: true, - get() { - broke = true; - return undefined; - }, -}; -/** - * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s - * constructor, computed from the internals object itself and cached there on - * first read. One accessor per constructor rather than one per instance. - */ -function defineLazyInternal(inst, key, compute) { - const proto = Object.getPrototypeOf(inst._zod); - if (key in proto && installing !== inst._zod) { - // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. - installing = undefined; - return; - } - installing = inst._zod; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. - Object.defineProperty(this, key, breaker); - const outer = broke; - broke = false; - try { - const value = compute(this); - // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. - if (broke) - delete this[key]; - else - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - broke = broke || outer; - return value; - } - catch (err) { - // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. - delete this[key]; - broke = broke || outer; - throw err; - } - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - }, - }); -} -/** - * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own - * data property. One accessor per constructor rather than one per instance, because an own accessor - * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. - */ -function installLazyProp(inst, key, make, enumerable) { - const proto = claim(inst, key); - if (!proto) - return; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. - const desc = { configurable: true, writable: true, enumerable, value: undefined }; - Object.defineProperty(this, key, desc); - // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches - desc.value = make(this); - Object.defineProperty(this, key, desc); - return desc.value; - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); - }, - }); -} -/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ -const CONSTANT_CATCH = "~constantCatch"; -/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ -function constantCatch(value) { - const fn = () => value; - fn[CONSTANT_CATCH] = true; - return fn; -} - -var core_a; - -/** A special constant with type `never` */ -const NEVER = /*@__PURE__*/ Object.freeze({ - status: "aborted", -}); -/* Shared descriptor for installing `_zod`; defineProperty reads it - * synchronously, so reusing one object avoids a per-instance allocation. */ -const _zodDesc = { value: undefined, enumerable: false }; -// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error -let _E = "captureStackTrace" in Error ? Error : null; -// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot -function newError(Definition) { - const E = _E; - if (E) { - const saved = E.stackTraceLimit; - if (typeof saved === "number") { - try { - E.stackTraceLimit = 0; - } - catch { - _E = null; - return new Definition(); - } - try { - return new Definition(); - } - finally { - E.stackTraceLimit = saved; - } - } - } - return new Definition(); -} -function $constructor(name, initializer, -/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ -proto, params) { - // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. - const zodProto = {}; - // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. - function Internals(def) { - this.def = def; - this.constr = _; - this.traits = new Set(); - } - Internals.prototype = zodProto; - const protoMembers = proto; - // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. - const initialized = protoMembers && new WeakSet(); - function init(inst, def) { - if (!inst._zod) { - _zodDesc.value = new Internals(def); - try { - Object.defineProperty(inst, "_zod", _zodDesc); - } - finally { - // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. - _zodDesc.value = undefined; - } - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - if (initialized) { - // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. - const own = Object.getPrototypeOf(inst); - const ctorProto = inst._zod.constr.prototype; - let up = own; - while (up && up !== ctorProto) - up = Object.getPrototypeOf(up); - const target = up ?? own; - if (!initialized.has(target)) { - initialized.add(target); - util_members(target, protoMembers); - } - } - // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype - const proto = _.prototype; - for (const k in proto) { - if (!Object.prototype.hasOwnProperty.call(proto, k)) - continue; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - const inst = params?.Parent ? newError(Definition) : this; - init(inst, def); - const deferred = inst._zod.deferred; - if (deferred) { - for (const fn of deferred) { - fn(); - } - // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. - inst._zod.deferred = undefined; - } - // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. - const pp = globalThis.__zod_globalConfig?.postProcessor; - if (pp) - pp(inst); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); -const globalConfig = globalThis.__zod_globalConfig; -function core_config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -class $ZodCyclicError extends Error { - constructor() { - super(`Cannot parse a reference cycle that closes through a transform`); - this.name = "ZodCyclicError"; - } -} -/** Keyed off the context object every schema in one parse call already shares. */ -const STATE = "~memo"; -const NO_ISSUES = []; -// Receivers prefix paths in place, so the cache and every hand-out need their own copies. -function cloneIssues(issues) { - return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); -} -const recursive = /*@__PURE__*/ new WeakMap(); -/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ -function isRecursive(inst, stack) { - const cached = recursive.get(inst); - if (cached !== undefined) - return cached; - // Relative to the walk in progress, so not cached. - if (stack.has(inst)) - return true; - stack.add(inst); - let result = false; - const check = (child) => { - if (!result && child?._zod && isRecursive(child, stack)) - result = true; - }; - const def = inst._zod.def; - const kind = def.type; - switch (kind) { - case "object": { - // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen - for (const key of Reflect.ownKeys(def.shape)) - check(def.shape[key]); - check(def.catchall); - break; - } - case "array": - check(def.element); - break; - case "tuple": - for (const el of def.items) - check(el); - check(def.rest); - break; - case "record": - case "map": - check(def.keyType); - check(def.valueType); - break; - case "set": - check(def.valueType); - break; - case "union": - for (const el of def.options) - check(el); - break; - case "intersection": - check(def.left); - check(def.right); - break; - case "optional": - case "nullable": - case "default": - case "prefault": - case "catch": - case "readonly": - case "nonoptional": - case "promise": - case "success": - check(def.innerType); - break; - case "pipe": - check(def.in); - check(def.out); - break; - case "function": - check(def.input); - check(def.output); - break; - // reading `_zod.innerType` resolves the getter once and caches it - case "lazy": - check(inst._zod.innerType); - break; - // a leaf by choice: `parts` are regex fragments, not data positions - case "template_literal": - // leaves - case "string": - case "number": - case "int": - case "boolean": - case "bigint": - case "symbol": - case "undefined": - case "null": - case "void": - case "never": - case "any": - case "unknown": - case "date": - case "nan": - case "enum": - case "literal": - case "file": - case "transform": - case "custom": - break; - default: { - // a new built-in kind becomes a compile error here - kind; - // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code - for (const key in def) { - const desc = Object.getOwnPropertyDescriptor(def, key); - if (!desc || desc.get) - continue; - const value = desc.value; - if (!value || typeof value !== "object") - continue; - if (value._zod) - check(value); - else if (Array.isArray(value)) - for (const el of value) - check(el); - } - } - } - stack.delete(inst); - recursive.set(inst, result); - return result; -} -/** - * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. - * Exported for `z.compile`, which refuses to compile such a schema: cycle - * breaking is driven from here off state keyed on the parse context, and a - * generated fast path has no context to key on. - */ -function isRecursiveSchema(inst) { - return isRecursive(inst, new Set()); -} -function bucketFor(state, inst) { - let bucket = state.buckets.get(inst); - if (!bucket) { - bucket = new Map(); - state.buckets.set(inst, bucket); - } - return bucket; -} -// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. -let handoff; -// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. -const memoizer_open = []; -const memoizer_memo = { - alloc(_inst, payload, empty) { - const bucket = handoff; - if (!bucket) - return empty; - handoff = undefined; - const entry = { value: empty, issues: null }; - bucket.set(payload.value, entry); - memoizer_open.push(entry); - return empty; - }, - guard(inst) { - var _a; - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. - if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) - throw new $ZodCyclicError(); - return base(payload, ctx); - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, - attach(inst) { - var _a; - let isRecursiveInst; - // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes - let lastCtx; - let lastBucket; - // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - if (isRecursiveInst === undefined) { - isRecursiveInst = isRecursive(inst, new Set()); - if (!isRecursiveInst) { - // Nothing here can ever fire, so take it back out. - inst._zod.parse = base; - if (inst._zod.run === wrapped) - inst._zod.run = base; - return base(payload, ctx); - } - } - const input = payload.value; - if (input === null || typeof input !== "object") - return base(payload, ctx); - let state = ctx[STATE]; - if (!state) { - state = { buckets: new Map(), backEdges: undefined }; - ctx[STATE] = state; - } - let bucket; - if (lastCtx === ctx) { - bucket = lastBucket; - } - else { - bucket = bucketFor(state, inst); - lastCtx = ctx; - lastBucket = bucket; - } - const hit = bucket.get(input); - if (hit) { - payload.value = hit.value; - if (hit.issues) { - if (hit.issues.length) - payload.issues.push(...cloneIssues(hit.issues)); - } - else { - // Still being parsed: its own checks cover it, so skip them here. - payload.memo = true; - state.backEdges ?? (state.backEdges = new Set()); - state.backEdges.add(hit.value); - } - return payload; - } - handoff = bucket; - const depth = memoizer_open.length; - const result = base(payload, ctx); - handoff = undefined; - // A container that rejected its input outright allocated nothing. - const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; - // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. - if (result instanceof Promise) { - return result.then((r) => { - if (entry) - entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; - return r; - }); - } - if (entry) - entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; - return result; - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, -}; -/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ -function memoizer() { - return memoizer_memo; -} -/** Whether this value is a node a back-edge resolved to before it finished. */ -function isBackEdge(ctx, value) { - const backEdges = ctx[STATE]?.backEdges; - return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); -} - - -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const cuid = /^[cC][0-9a-z]{6,}$/; -const cuid2 = /^[0-9a-z]+$/; -const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; -const xid = /^[0-9a-vA-V]{20}$/; -const ksuid = /^[A-Za-z0-9]{27}$/; -const nanoid = /^[a-zA-Z0-9_-]{21}$/; -function nanoidOfLength(length) { - return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); -} -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ -const extendedDuration = /^[-+]?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)?)??$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. - * - * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -const uuid = (version) => { - if (!version) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); -const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); -const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); -/** Practical email validation */ -const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -/** The classic emailregex.com regex for RFC 5322-compliant emails */ -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. -const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const regexes_ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/; -const mac = (delimiter) => { - const escapedDelim = util.escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const regexes_base64url = /^[A-Za-z0-9_-]*$/; -// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address -// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; -const httpProtocol = /^https?$/; -// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 -const e164 = /^\+[1-9]\d{6,14}$/; -// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). -const creditCard = /^\d(?:[ -]?\d){11,18}$/; -const dateSource = `(?:(?:\\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])))`; -/** Anchors a pattern source. The interpolation lives here rather than at the call site because - * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it - * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ -function regexes_anchor(source) { - return new RegExp(`^${source}$`); -} -const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : args.seconds - ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function regexes_time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetime(args) { - const opts = ["Z"]; - // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them - const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; - const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const regexes_string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number = /^-?\d+(?:\.\d+)?$/; -const regexes_boolean = /^(?:true|false)$/i; -const _null = /^null$/i; - -const _undefined = /^undefined$/i; - -// regex for string with no uppercase letters -const lowercase = /^[^A-Z]*$/; -// regex for string with no lowercase letters -const uppercase = /^[^a-z]*$/; -// regex for hexadecimal strings (any length) -const regexes_hex = /^[0-9a-fA-F]*$/; -// Hash regexes for different algorithms and encodings -// Helper function to create base64 regex with exact length and padding -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -// Helper function to create base64url regex with exact length (no padding) -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -// MD5 (16 bytes): base64 = 24 chars total (22 + "==") -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); -const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); -// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); -const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); -// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); -const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); -// SHA384 (48 bytes): base64 = 64 chars total (no padding) -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); -const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); -// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); -const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); - -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ -const _whenHasSize = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; -}; -/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ -const _whenHasLength = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; -}; -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = -/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN - def.value !== BigInt(0) && payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: util.getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. - const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. - const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 - ? codePointLength(input) - : units; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. - const length = typeof input === "string" && units >= def.length && units <= def.length * 2 - ? codePointLength(input) - : units; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - // `String.prototype.includes(sub, position)` matches `sub` at `position` - // OR LATER, so the pattern must allow at least `position` leading chars - // (`{N,}`), not exactly `position` chars (`{N}`). - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}))); -const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -class Doc { - constructor(args = [], closed = {}) { - this.content = []; - this.indent = 0; - this.args = args; - this.closed = closed; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const content = this?.content ?? [``]; - const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); - return factory(...Object.values(this.closed)); - } -} - - - -/* Computing the message eagerly is expensive (pretty-printed JSON of all - * issues), so defer it until first read. The accessor functions and - * descriptors are shared across instances to keep error construction - * cheap; the computed message is cached on the internals object. The - * setter preserves plain assignment semantics for consumers that - * overwrite `message`. */ -function _getMessage() { - const internals = this._zod; - internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); - return internals.message; -} -function _setMessage(value) { - this._zod.message = value; -} -const _messageDesc = { - get: _getMessage, - set: _setMessage, - enumerable: true, - configurable: true, -}; -const errors_zodDesc = { value: undefined, enumerable: false }; -const _issuesDesc = { value: undefined, enumerable: false }; -/* Prototypes that already carry the lazy `toString`. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -const errors_initializer = (inst, def) => { - inst.name = "$ZodError"; - errors_zodDesc.value = inst._zod; - Object.defineProperty(inst, "_zod", errors_zodDesc); - _issuesDesc.value = def; - Object.defineProperty(inst, "issues", _issuesDesc); - // Clear the shared slots; a retained `value` pins the last error's issues. - errors_zodDesc.value = undefined; - _issuesDesc.value = undefined; - Object.defineProperty(inst, "message", _messageDesc); - /* `toString` lives as a non-enumerable lazy getter on the shared - * prototype; on first access it caches a per-instance closure so - * detached usage still works. */ - const proto = Object.getPrototypeOf(inst); - if (!_installedToString.has(proto)) { - _installedToString.add(proto); - Object.defineProperty(proto, "toString", { - configurable: true, - enumerable: false, - get() { - const value = () => this.message; - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - }, - }); - } -}; -const $ZodError = $constructor("$ZodError", errors_initializer); -const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { - Parent: Error, -}); -/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member - * ("toString", "constructor") would otherwise read through to the prototype, and assigning - * "__proto__" would hit the setter instead of creating a key. */ -function errors_node(obj, key, make) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - if (key === "__proto__") { - Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); - } - else { - obj[key] = make(); - } - } - return obj[key]; -} -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. - if (el === "_errors") { - if (terminal) - curr._errors.push(mapper(issue)); - i++; - continue; - } - // A path element may collide with an inherited property name such as - // "__proto__" or "constructor". Truthiness checks read the prototype - // (so no node is created, then ._errors.push throws), and bracket - // assignment of "__proto__" hits the setter instead of creating an - // own key. Guard the read with hasOwnProperty and create the node - // with defineProperty so any path element becomes a real own key. - if (!Object.prototype.hasOwnProperty.call(curr, el)) { - Object.defineProperty(curr, el, { - value: { _errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - const node = curr[el]; - if (terminal) { - node._errors.push(mapper(issue)); - } - curr = node; - i++; - } - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - // el may collide with an inherited property name ("__proto__", - // "constructor", ...); ??= reads the prototype so the node is never - // created and curr.errors.push throws. Guard with hasOwnProperty and - // create the node with defineProperty so "__proto__" becomes a real - // own key rather than invoking the prototype setter. - if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { - Object.defineProperty(curr.properties, el, { - value: { errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - - - - -// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. -function finalizeParams(callee, params) { - return { callee: params?.callee ?? callee, Err: params?.Err }; -} -const parse_parse = (_Err) => { - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, _params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); -const parse_parseAsync = (_Err) => { - const fn = async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); -// registry mirrors of the compiler's sentinels, so this module never imports the compiler -const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); -const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); -// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. -const parse_validate = ((schema, value, _ctx) => { - const validator = schema._zod.bag.validator; - if (validator !== undefined && validator(value) !== COMPILE_INVALID) - return true; - return validateFallback(schema, value, _ctx); -}); -function validateFallback(schema, value, _ctx) { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const fallbackRun = schema._zod.bag.fallbackRun; - let result; - if (fallbackRun) { - // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound - ctx[COMPILE_FALLBACK] = true; - result = fallbackRun({ value, issues: [] }, ctx); - } - else { - result = schema._zod.run({ value, issues: [] }, ctx); - } - if (result instanceof Promise) { - throw new core.$ZodAsyncError(); - } - return result.issues.length === 0; -} -// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw -const parse_validateAsync = async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length === 0; -}; -const parse_encode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return parse(schema, value, ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const encode = /* @__PURE__*/ parse_encode($ZodRealError); -const parse_decode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - return parse(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decode = /* @__PURE__*/ parse_decode($ZodRealError); -const parse_encodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); - }; - return fn; -}; -const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); -const parse_decodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); - -const versions_version = { - major: 4, - minor: 5, - patch: 4, -}; - - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const defChecks = inst._zod.def.checks; - // if inst is itself a checks.$ZodCheck, run it as a check - const checks = inst._zod.traits.has("$ZodCheck") - ? [inst, ...(defChecks ?? [])] - : defChecks?.length - ? [...defChecks] - : []; - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - if (payload.memo) - return payload; - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) - continue; - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - // abort if the canary is aborted - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - // run checks first, then - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - // run canary initial pass (no checks) - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - // forward - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } -}, { - // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. - get "~standard"() { - return hide(this, "~standard", standardProps(this)); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, -}); -/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ -const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; -function standardProps(inst) { - return { - validate: (value) => { - try { - return toStandardResult(safeParse(inst, value)); - } - catch (_) { - return safeParseAsync(inst, value).then(toStandardResult); - } - }, - vendor: "zod", - version: 1, - }; -} - -const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } - else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -/** The `://` guard rejected the input before the URL constructor saw it. */ -const URL_BAD_FORMAT = 1; -/** The URL constructor rejected the input. */ -const URL_UNPARSEABLE = 2; -/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ -function parseURLObject(trimmed, def) { - // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted - if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { - return URL_BAD_FORMAT; - } - try { - // @ts-ignore - return new URL(trimmed); - } - catch { - return URL_UNPARSEABLE; - } -} -const asciiTabOrNewline = /[\t\n\r]/g; -/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ -function stripTabAndNewline(value) { - return value.replace(asciiTabOrNewline, ""); -} -function urlHostnameOk(url, hostname) { - hostname.lastIndex = 0; - return hostname.test(url.hostname); -} -function urlProtocolOk(url, protocol) { - protocol.lastIndex = 0; - return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); -} -const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - // Trim whitespace from input - const trimmed = payload.value.trim(); - const url = parseURLObject(trimmed, def); - if (url === URL_BAD_FORMAT) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (url === URL_UNPARSEABLE) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (def.hostname && !urlHostnameOk(url, def.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - if (def.protocol && !urlProtocolOk(url, def.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - // Set the output value based on normalize flag - payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) - throw new Error(`Invalid nanoid length: ${def.length}`); - def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); - $ZodStringFormat.init(inst, def); -}); -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema - if (def.local || def.precision === -1) { - inst._zod.bag.laxFormat = true; - inst._zod.onattach.push((s) => { - s._zod.bag.laxFormat = true; - }); - } -}); -const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = regexes_date); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes_time(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ -const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; -function isValidIPv6(value) { - if (!ipv6Alphabet.test(value)) - return false; - try { - // @ts-ignore - new URL(`http://[${value}]`); - return true; - } - catch { - return false; - } -} -const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes_ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - if (!isValidIPv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}))); -const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -function isValidCIDRv6(value) { - const parts = value.split("/"); - if (parts.length !== 2) - return false; - const [address, prefix] = parts; - if (!prefix) - return false; - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - return false; - if (prefixNum < 0 || prefixNum > 128) - return false; - return isValidIPv6(address); -} -const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (!isValidCIDRv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - // atob ignores whitespace, so reject it up front. - if (/\s/.test(data)) - return false; - if (data.length % 4 !== 0) - return false; - try { - // @ts-ignore - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!regexes_base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -////////////////////////////// ZodCreditCard ////////////////////////////// -const CC_SANITIZE = /[- ]/g; -/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ -function isLuhnAlgo(digits) { - let length = digits.length; - let bit = 1; - let sum = 0; - while (length) { - const value = +digits[--length]; - bit ^= 1; - sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; - } - return sum % 10 === 0; -} -function isValidCreditCard(input) { - if (!regexes.creditCard.test(input)) - return false; - return isLuhnAlgo(input.replace(CC_SANITIZE, "")); -} -const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { - // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. - def.pattern ?? (def.pattern = regexes.creditCard); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidCreditCard(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "credit_card", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - // @ts-ignore - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? String(input) - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checks -}); -const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes_boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { - checks.$ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}))); -const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.undefined; - inst._zod.values = new Set([undefined]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}))); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handlePropertyResult(result, final, key, input, optin, optout) { - const isPresent = key in input; - const isOptionalOut = optout === "optional"; - // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. - if (!isPresent && isOptionalOut && optin === "optional") { - return; - } - if (result.issues.length) { - // For optional-in/out schemas, ignore errors on absent keys. - if (optin !== undefined && isOptionalOut && !isPresent) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && optin === undefined) { - if (!result.issues.length) { - final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [key], - }); - } - return; - } - if (result.value === undefined) { - if (isPresent) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -// one shared instance; a fresh [] per schema cost 56 bytes retained -const NO_SYMBOL_KEYS = []; -function normalizeDef(def) { - const keys = Object.keys(def.shape); - const ownSymbols = Object.getOwnPropertySymbols(def.shape); - const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; - // aliases `keys` when there are no symbols, so a string-only shape keeps one array - const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; - for (const k of allKeys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - allKeys, - symbolKeys, - // string-only: handleCatchall matches it against `for...in`, which never yields a symbol - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const optin = _catchall.optin; - const optout = _catchall.optout; - for (const key in input) { - // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. - if (keySet.has(key)) - continue; - // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. - if (key === "__proto__") { - if (t === "never") - unrecognized.push(key); - continue; - } - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. - continue: true, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. -const propShapes = new WeakMap(); -const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - // const sh = def.shape; - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - propShapes.set(def, sh); - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - propShapes.set(def, newSh); - return newSh; - }, - }); - } - const _normalized = util_cached(() => normalizeDef(def)); - defineLazyInternal(inst, "propValues", (zod) => { - const shape = zod.def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - if (!Object.prototype.hasOwnProperty.call(propValues, key)) { - assignProp(propValues, key, new Set()); - } - for (const v of field.values) - propValues[key].add(v); - // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. - if (field.optin !== undefined) - propValues[key].add(undefined); - } - } - return propValues; - }); - const isObject = util_isObject; - const catchall = def.catchall; - let value; - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const proms = []; - const shape = value.shape; - for (const key of value.allKeys) { - if (key === "__proto__") - continue; - const el = shape[key]; - const optin = el._zod.optin; - const optout = el._zod.optout; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = util_cached(() => normalizeDef(def)); - const memo = globalConfig.memoizer; - const generateFastpass = (shape) => { - const normalized = _normalized.value; - const syms = normalized.symbolKeys; - // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope - const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); - const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - // Prefixes in place, like util.prefixIssues does for every interpreted path. - const prefixStr = (id, k) => ` - for (let i = 0; i < ${id}.issues.length; i++) { - const iss = ${id}.issues[i]; - iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; - payload.issues.push(iss); - }`; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.allKeys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); - for (const key of normalized.allKeys) { - if (key === "__proto__") - continue; - const id = ids[key]; - const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); - const isPresent = `${k} in input`; - const schema = shape[key]; - const optin = schema?._zod?.optin; - const isOptionalIn = optin !== undefined; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(k)};`); - if (isOptionalIn && isOptionalOut) { - // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. - const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; - doc.write(` - const ${id}_present = ${isPresent}; - if (!${id}.issues.length || ${id}_present) { - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${assign}) { - newResult[${k}] = ${id}.value; - } - } - - `); - } - else if (!isOptionalIn) { - doc.write(` - const ${id}_present = ${isPresent}; - if (${id}.issues.length) {${prefixStr(id, k)} - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - newResult[${k}] = ${id}.value; - } - - `); - } - else { - doc.write(` - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${id}.value === undefined) { - if (${isPresent}) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone - return doc.compile(); - }; - let fastpass; - const isObject = util_isObject; - const jit = !globalConfig.jitless; - const allowsEval = util_allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") - ? "defaulted" - : zod.def.options.some((o) => o._zod.optin !== undefined) - ? "optional" - : undefined); - defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazyInternal(inst, "values", (zod) => { - if (zod.def.options.every((o) => o._zod.values)) { - return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - if (zod.def.options.every((o) => o._zod.pattern)) { - const patterns = zod.def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const matches = []; - for (let i = 0; i < results.length; i++) { - if (results[i].issues.length === 0) - matches.push(i); - } - if (matches.length === 1) { - final.value = results[matches[0]].value; - return final; - } - if (matches.length === 0) { - // No matches - same as regular union - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), - }); - } - else { - // Multiple matches - exclusive union failure - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - matches, - }); - } - return final; -} -const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}))); -/** Returns the option of `union` whose discriminator claims `value`. */ -function getDiscriminatedOption(union, value) { - const internals = union._zod; - let map = internals.bag.optionsMap; - if (!map) { - map = new Map(); - const { options, discriminator } = internals.def; - for (const option of options) { - // First declaration wins, matching the order the parse path resolves a duplicate in. - for (const v of option._zod.propValues?.[discriminator] ?? []) - if (!map.has(v)) - map.set(v, option); - } - internals.bag.optionsMap = map; - } - return map.get(value); -} -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazyInternal(inst, "propValues", (zod) => { - const propValues = {}; - for (const option of zod.def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!Object.prototype.hasOwnProperty.call(propValues, k)) { - assignProp(propValues, k, new Set()); - } - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. - def.options.forEach((option, i) => { - const propShape = propShapes.get(option._zod.def); - if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { - throw new Error(`Invalid discriminated union option at index "${i}"`); - } - }); - const disc = util_cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util_isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - // Fall back to union matching when the fast discriminator path fails: - // - explicitly enabled via unionFallback, or - // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions - if (def.unionFallback || ctx.direction === "backward") { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function schemas_mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) - delete newObj.__proto__; - for (const key of sharedKeys) { - if (key === "__proto__") - continue; - const sharedValue = schemas_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = schemas_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. - const unrecKeys = new Map(); - let unrecIssue; - const keyIssues = new Map(); - const collect = (iss, side) => { - let keys; - if (iss.code === "unrecognized_keys" && !iss.path?.length) { - unrecIssue ?? (unrecIssue = iss); - keys = iss.keys; - } - else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { - const k = String(iss.path[0]); - if (!keyIssues.has(k)) - keyIssues.set(k, iss); - keys = [k]; - } - else { - return false; - } - for (const k of keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k)[side] = true; - } - return true; - }; - for (const iss of left.issues) { - if (!collect(iss, "l")) - result.issues.push(iss); - } - for (const iss of right.issues) { - if (!collect(iss, "r")) - result.issues.push(iss); - } - // Report only keys rejected by BOTH sides - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length) { - const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; - if (aggregated.length) - result.issues.push({ ...unrecIssue, keys: aggregated }); - for (const k of bothKeys) { - if (!aggregated.includes(k) && keyIssues.has(k)) - result.issues.push(keyIssues.get(k)); - } - } - const merged = schemas_mergeValues(left.value, right.value); - if (!merged.valid) { - if (aborted(result)) - return result; - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; - const proms = []; - const optinStart = getTupleOptStart(items, "optin"); - const optoutStart = getTupleOptStart(items, "optout"); - if (!def.rest) { - if (input.length < optinStart) { - payload.issues.push({ - code: "too_small", - minimum: optinStart, - inclusive: true, - input, - inst, - origin: "array", - }); - return payload; - } - if (input.length > items.length) { - payload.issues.push({ - code: "too_big", - maximum: items.length, - inclusive: true, - input, - inst, - origin: "array", - }); - } - } - // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. - const itemResults = new Array(items.length); - for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((rr) => { - itemResults[i] = rr; - })); - } - else { - itemResults[i] = r; - } - } - if (def.rest) { - let i = items.length - 1; - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ value: el, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((r) => handleTupleResult(r, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); - } - return handleTupleResults(itemResults, payload, items, input, optoutStart); - }; -}))); -function getTupleOptStart(items, key) { - for (let i = items.length - 1; i >= 0; i--) { - // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. - const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; - if (!omittable) - return i + 1; - } - return 0; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...util.prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleTupleResults(itemResults, final, items, input, optoutStart) { - // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. - for (let i = 0; i < items.length; i++) { - const r = itemResults[i]; - const isPresent = i < input.length; - // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. - if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { - final.value.length = i; - break; - } - if (r.issues.length) { - if (!isPresent && i >= optoutStart) { - final.value.length = i; - break; - } - final.issues.push(...util.prefixIssues(i, r.issues)); - } - final.value[i] = r.value; - } - // Drop trailing slots that produced `undefined` for absent input - // (the array analog of an absent optional key on an object). The - // `i >= input.length` floor is critical: an explicit `undefined` - // *inside* the input must be preserved even when the schema is - // optional-out (e.g. `z.string().or(z.undefined())` accepting an - // explicit undefined value). - for (let i = final.value.length - 1; i >= input.length; i--) { - if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { - final.value.length = i; - } - else { - break; - } - } - return final; -} -const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values && !def.partial) { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - // A declared __proto__ is stripped but is not an unrecognized key. - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - continue; - } - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - if (def.mode === "loose") { - // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into - if (key === "__proto__") - continue; - payload.value[key] = input[key]; - } - else { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - else { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. - let unrecognized; - // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - // Pass through unchanged - payload.value[key] = input[key]; - } - else if (values) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - else { - // Default "strict" behavior: error on invalid key - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - if (valueResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - const values = new Set(def.values); - inst._zod.values = values; - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(def.values.length - ? `^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$` - : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - // @ts-ignore - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - globalConfig.memoizer?.guard(inst); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(payload, result) { - // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. - payload.value = result.issues.length ? undefined : result.value; - return payload; -} -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - inst._zod.optout = "optional"; - defineLazyInternal(inst, "values", (zod) => { - const values = zod.def.innerType._zod.values; - return values ? new Set([...values, undefined]) : undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. - if (def.innerType._zod.optin !== "defaulted") - return payload; - // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) - return result.then((result) => handleOptionalResult(payload, result)); - return handleOptionalResult(payload, result); - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - // Call parent init - inherits optin/optout = "optional" - $ZodOptional.init(inst, def); - // Override values/pattern to NOT add undefined - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); - // Override parse to just delegate (no undefined handling) - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazyInternal(inst, "values", (zod) => { - return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - // Forward direction (decode): allow null to pass through - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply defaults for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - // Forward direction: continue with default handling - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply prefault for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => { - const v = zod.def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new core.$ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}))); -function handleCatchResult(payload, result, def, ctx) { - if (!result.issues.length) { - payload.value = result.value; - // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. - if (result.memo) - payload.memo = true; - return payload; - } - // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. - payload.value = def.catchValue({ - ...result, - value: payload.value, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - }, - input: payload.value, - }); - return payload; -} -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply catch logic - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) { - return result.then((result) => handleCatchResult(payload, result, def, ctx)); - } - return handleCatchResult(payload, result, def, ctx); - }; -}); -const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}))); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. - if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { - // prevent further checks - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}))); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - // prevent further checks - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - // Check if transform added any issues - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { - $ZodPipe.init(inst, def); -}); -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. - if (!payload.memo) - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - // is Zod schema - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || util.primitiveTypes.has(typeof part)) { - regexParts.push(util.escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}))); -const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. - Object.defineProperty(inst, "_def", { value: def }); - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. - return Object.defineProperty(function (...args) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return Object.defineProperty(async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - // Check if output is a promise type to determine if we should use async implementation - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}))); -const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}))); -const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. - defineLazy(inst._zod, "innerType", () => { - const d = def; - if (!d._cachedInner) - d._cachedInner = def.getter(); - return d._cachedInner; - }); - defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); - defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); - defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); - defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -var registries_a; -const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); -const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registries_registry() { - return new $ZodRegistry(); -} -(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - - - - - -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link _cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _creditCard(Class, params) { - return new Class({ - type: "string", - format: "credit_card", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = (/* unused pure expression or super */ null && ({ - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -})); -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_undefined(Class, params) { - return new Class({ - type: "undefined", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_null(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ - type: "any", - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class, params) { - return new Class({ - type: "void", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class, params) { - return new Class({ - type: "date", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class, params) { - return new Class({ - type: "nan", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return _gt(0, params); -} -// negative -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return _lt(0, params); -} -// nonpositive -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new checks.$ZodCheckMaxSize({ - check: "max_size", - ...util.normalizeParams(params), - maximum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new checks.$ZodCheckMinSize({ - check: "min_size", - ...util.normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new checks.$ZodCheckSizeEquals({ - check: "size_equals", - ...util.normalizeParams(params), - size, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema, params) { - return new checks.$ZodCheckProperty({ - check: "property", - property, - schema, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _properties(shape) { - return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new checks.$ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -// @__NO_SIDE_EFFECTS__ -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -// slugify -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...util.normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options: options, - discriminator, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -// @__NO_SIDE_EFFECTS__ -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof schemas.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class, params) { - return new Class({ - type: "file", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); - }, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class, fn, _params) { - const norm = util.normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// same as _custom but defaults to abort:false -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = _check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function api_meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = util.normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? schemas.$ZodCodec; - const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; - const _String = Classes.String ?? schemas.$ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - codec._zod.bag.truthy = truthyArray; - codec._zod.bag.falsy = falsyArray; - codec._zod.bag.case = params.case ?? "insensitive"; - return codec; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = util.normalizeParams(_params); - const def = { - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - - - -function assignProps(target, ...sources) { - for (const source of sources) { - for (const key of Reflect.ownKeys(source)) { - if (Object.prototype.propertyIsEnumerable.call(source, key)) { - assignProp(target, key, source[key]); - } - } - } - return target; -} -// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { -// return { -// processor: inputs.processor, -// metadataRegistry: inputs.metadata ?? globalRegistry, -// target: inputs.target ?? "draft-2020-12", -// unrepresentable: inputs.unrepresentable ?? "throw", -// }; -// } -function initializeContext(params) { - // Normalize target: convert old non-hyphenated versions to hyphenated versions - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - sharedDefsExtractedFor: undefined, - sharedEmitDoneFor: undefined, - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - intersections: [], - deferred: [], - external: params?.external ?? undefined, - }; -} -/** - * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws - * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a - * custom JSON Schema was written into `json`, in which case the caller must not write its own. - */ -function handleUnrepresentable(schema, ctx, json, params, message) { - const result = typeof ctx.unrepresentable === "function" - ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) - : ctx.unrepresentable; - if (result === "any") - return false; - if (result === undefined || result === "throw") - throw new Error(message); - Object.assign(json, result); - return true; -} -function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - // check for schema in seens - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - ctx.sharedDefsExtractedFor = undefined; - ctx.sharedEmitDoneFor = undefined; - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - // Also set ref if processor didn't (for inheritance) - if (!result.ref) - result.ref = parent; - to_json_schema_process(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - // metadata - const meta = ctx.metadataRegistry.get(schema); - if (meta) - assignProps(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (ctx.io === "input" && "_prefault" in result.schema) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from ctx.seen in case it was overwritten - const _result = ctx.seen.get(schema); - return _result.schema; -} -// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. -function encodeJSONPointerSegment(segment) { - return segment.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function extractDefs(ctx, schema -// params: EmitParams -) { - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. - if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) - return; - // Track ids to detect duplicates across different schemas - const idToSchema = new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy - // external is configured - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; - // check if schema is in the external registry - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` - if (entry[1] === root && !entry[1].schema.id) { - return { ref: uriPrefix }; - } - // self-contained schema - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; - }; - // stored cached version in `def` property remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } - if (ctx.external) - ctx.sharedDefsExtractedFor = ctx.external; -} -/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ -function compactTypeUnion(schema) { - const options = schema.anyOf; - if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) - return; - const types = []; - for (const option of options) { - if (!option || typeof option !== "object") - return; - // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. - compactTypeUnion(option); - const keys = Object.keys(option); - if (keys.length !== 1 || keys[0] !== "type") - return; - const type = option.type; - for (const member of Array.isArray(type) ? type : [type]) { - if (typeof member !== "string") - return; - if (!types.includes(member)) - types.push(member); - } - } - delete schema.anyOf; - // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. - schema.type = types.length === 1 ? types[0] : types; -} -/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, - * an annotation like `description` — makes a member unfoldable, so a constraint this does not - * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ -const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); -const UNION_KEYS = ["oneOf", "anyOf"]; -/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ -function undeclaredConstraint(member) { - const extra = member.additionalProperties; - if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) - return null; - return Object.keys(extra).length ? extra : null; -} -/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ -function foldObjects(members) { - const objects = []; - for (const member of members) { - // A boolean subschema is legal JSON Schema and carries no keywords to fold. - if (typeof member !== "object" || member.type !== "object") - return null; - for (const key in member) { - if (!FOLDABLE_KEYS.has(key)) - return null; - } - objects.push(member); - } - const properties = {}; - const required = new Set(); - for (const object of objects) { - for (const key in object.properties) { - // `in` would report a `__proto__` key as already present via the prototype chain and skip it. - if (Object.prototype.hasOwnProperty.call(properties, key)) - continue; - // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. - const parts = []; - for (const other of objects) { - const part = other.properties?.[key] ?? undeclaredConstraint(other); - if (part === null || part === undefined) - continue; - if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) - parts.push(part); - } - const merged = parts.length === 1 - ? parts[0] - : (foldObjects(parts) ?? { allOf: parts }); - assignProp(properties, key, merged); - } - for (const key of object.required ?? []) - required.add(key); - } - const folded = { type: "object", properties }; - if (required.size) - folded.required = [...required]; - // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. - if (objects.every((object) => object.additionalProperties === false)) { - folded.additionalProperties = false; - } - else { - const constraints = []; - for (const object of objects) { - const constraint = undeclaredConstraint(object); - if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) - constraints.push(constraint); - } - if (constraints.length === 1) - folded.additionalProperties = constraints[0]; - else if (constraints.length > 1) - folded.additionalProperties = { allOf: constraints }; - } - return folded; -} -/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two - * closed object members reject each other's keys and the schema validates nothing. Zod's parser - * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when - * *every* side rejects it — so the emitted schema has to pool them too, and folding the members - * into one object is the encoding that says so on every target. - * - * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` - * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it - * keeps its reference and its own closedness rather than being inlined as a stale copy. */ -function foldIntersection(json) { - const allOf = json.allOf; - if (!Array.isArray(allOf) || allOf.length < 2) - return; - // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. - for (const key of FOLDABLE_KEYS) - if (key in json) - return; - // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. - const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); - let folded = null; - if (!unions.length) { - folded = foldObjects(allOf); - } - else { - const union = unions[0]; - const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); - if (Object.keys(union).length !== 1) - return; - const rest = allOf.filter((m) => m !== union); - const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); - if (branches.some((b) => !b)) - return; - folded = { [keyword]: branches }; - } - if (!folded) - return; - delete json.allOf; - assignProps(json, folded); -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // flatten refs - inherit properties from parent schemas - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - // already processed - if (seen.ref === null) - return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; // prevent infinite recursion - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - // merge referenced schema into current - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - // older drafts can't combine $ref with other properties - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - assignProps(schema, refSchema); - } - // restore child's own properties (child wins) - assignProps(schema, _cached); - const isParentRef = zodSchema._zod.parent === ref; - // For parent chain, child is a refinement - remove parent-only properties - if (isParentRef) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema[key]; - } - } - } - // When ref was extracted to $defs, remove properties that match the definition - if (refSchema.$ref && refSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { - delete schema[key]; - } - } - } - } - // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - // Ensure parent is processed first so its def has inherited properties - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - // De-duplicate with parent's definition - if (parentSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema[key]; - } - } - } - } - } - // execute overrides - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - if (ctx.target !== "openapi-3.0") { - for (const entry of ctx.seen.entries()) { - compactTypeUnion(entry[1].def ?? entry[1].schema); - } - } - for (const rewrite of ctx.deferred) - rewrite(); - // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. - if (ctx.intersections.length) { - const carriers = new Map(); - for (const seen of ctx.seen.values()) { - for (const json of [seen.schema, seen.def]) { - const allOf = json?.allOf; - if (!Array.isArray(allOf)) - continue; - const existing = carriers.get(allOf); - if (existing) - existing.push(json); - else - carriers.set(allOf, [json]); - } - } - for (const allOf of ctx.intersections) { - for (const json of carriers.get(allOf) ?? []) - foldIntersection(json); - } - } - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") { - // OpenAPI 3.0 schema objects should not include a $schema property - } - else { - // Arbitrary string values are allowed but won't have a $schema property set - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs - assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); - // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== undefined && result.id === rootMetaId) - delete result.id; - // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. - const defs = ctx.external?.defs ?? {}; - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - assignProp(defs, seen.defId, seen.def); - } - } - } - if (ctx.external) - ctx.sharedEmitDoneFor = ctx.external; - // set definitions in result - if (ctx.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault" || - def.type === "catch") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) - return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -/** - * Creates a toJSONSchema method for a schema instance. - * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. - */ -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - - - - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set -}; -// ==================== SIMPLE TYPE PROCESSORS ==================== -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids - if (format === "time" || laxFormat) { - delete json.format; - } - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const patternList = [...patterns]; - if (patternList.length === 1) - json.pattern = patternList[0].source; - else if (patternList.length > 1) { - json.allOf = [ - ...patternList.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - // when both minimum and exclusiveMinimum exist, pick the more restrictive one - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) { - if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - else if (typeof minimum === "number") { - json.minimum = minimum; - } - if (exMax) { - if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - else if (typeof maximum === "number") { - json.maximum = maximum; - } - if (typeof multipleOf === "number") { - // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. - if (Number.isFinite(multipleOf) && multipleOf !== 0) - json.multipleOf = Math.abs(multipleOf); - else - handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); - } -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); -}; -const symbolProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); -}; -const voidProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const dateProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - // an empty enum accepts nothing, same as z.never() - if (values.length === 0) { - json.not = {}; - return; - } - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // a literal with no values accepts nothing, same as z.never() - if (def.values.length === 0) { - json.not = {}; - return; - } - const vals = []; - for (const val of def.values) { - if (val === undefined) { - // a custom schema replaces the whole literal, so there is nothing left to accumulate - if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) - return; - // otherwise do not add to vals - } - else if (typeof val === "bigint") { - if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) - return; - vals.push(Number(val)); - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - Object.assign(_json, file); // shared props at root - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); -}; -const functionProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); -}; -const transformProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); -}; -const mapProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); -}; -const setProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); -}; -// ==================== COMPOSITE TYPE PROCESSORS ==================== -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = to_json_schema_process(def.element, ctx, { - ...params, - path: [...params.path, "items"], - }); -}; -// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an -// absent key, but their declared input type stays required. An input JSON Schema describes the -// declared type, so resolve past them to the schema that actually carries the optionality. -// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see -// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". -function inputOptin(schema) { - const def = schema._zod.def; - if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { - return inputOptin(def.out); - } - if (def.type === "catch") { - return inputOptin(def.innerType); - } - return schema._zod.optin; -} -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const shape = def.shape; - // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires - const symbolKeys = Object.getOwnPropertySymbols(shape); - if (symbolKeys.length && - handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { - return; - } - json.type = "object"; - json.properties = {}; - for (const key in shape) { - // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into - assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - })); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const field = def.shape[key]; - if (ctx.io === "input") { - return inputOptin(field) === undefined; - } - else { - return field._zod.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = to_json_schema_process(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = to_json_schema_process(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = to_json_schema_process(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; - // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. - ctx.intersections.push(allOf); -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? to_json_schema_process(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - let minItems = def.items.length; - while (minItems > 0) { - const item = def.items[minItems - 1]; - const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; - if (!optional) - break; - minItems--; - } - const maxItems = def.items.length; - const isClosed = !def.rest; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (isClosed) { - json.items = false; - } - else if (rest) { - json.items = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else { - json.items = prefixItems; - if (isClosed) { - json.additionalItems = false; - } - else if (rest) { - json.additionalItems = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - // explicit user-defined length checks take precedence - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the - * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key - * behind a wrapper only carries its own `type` before then, and a union key only has its branches. - * - * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather - * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this - * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` - * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema - * outright. */ -function stringifyKeyNames(bySchema, json, visited) { - // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. - if (json.$ref) { - // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again - if (visited.has(json)) - return json; - visited.add(json); - const def = bySchema.get(json)?.def; - if (!def) - return json; - const inlined = stringifyKeyNames(bySchema, def, visited); - return inlined === def ? json : inlined; - } - for (const keyword of ["anyOf", "oneOf"]) { - const branches = json[keyword]; - if (!Array.isArray(branches)) - continue; - const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); - // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` - if (mapped.some((branch, i) => branch !== branches[i])) - json = { ...json, [keyword]: mapped }; - } - // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric - const types = Array.isArray(json.type) ? json.type : [json.type]; - const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); - // a heterogeneous key carries no type at all, so its numeric members are caught here instead - const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); - if (!numericType && !values?.some((v) => typeof v === "number")) - return json; - const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; - if (rest.enum) - rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); - else if (typeof rest.const === "number") - rest.const = String(rest.const); - // a heterogeneous key keeps its absent type: the stringified members already say what a key may be - if (!numericType) - return rest; - rest.type = "string"; - if (!values) - rest.pattern = (types.includes("number") ? number : integer).source; - return rest; -} -/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ -const pendingRecords = new WeakMap(); -function rewriteKeyNames(ctx) { - // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. - const bySchema = new Map(); - for (const entry of ctx.seen.values()) { - if (entry.def && !bySchema.has(entry.schema)) - bySchema.set(entry.schema, entry); - } - const rewrites = new Map(); - for (const record of pendingRecords.get(ctx) ?? []) { - const seen = ctx.seen.get(record); - const names = (seen?.def ?? seen?.schema)?.propertyNames; - if (!names || names === true || rewrites.has(names)) - continue; - const rewritten = stringifyKeyNames(bySchema, names, new Set()); - if (rewritten !== names) - rewrites.set(names, rewritten); - } - if (!rewrites.size) - return; - // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together - for (const entry of ctx.seen.values()) { - for (const carrier of [entry.schema, entry.def]) { - const rewritten = carrier && rewrites.get(carrier.propertyNames); - if (rewritten) - carrier.propertyNames = rewritten; - } - } -} -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - // Use patternProperties for looseRecord with regex patterns - const valueSchema = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"], - }); - json.patternProperties = {}; - for (const pattern of patterns) { - assignProp(json.patternProperties, pattern.source, valueSchema); - } - } - else { - // Default behavior: use propertyNames + additionalProperties - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = to_json_schema_process(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - let pending = pendingRecords.get(ctx); - if (!pending) { - pending = []; - pendingRecords.set(ctx, pending); - ctx.deferred.push(() => rewriteKeyNames(ctx)); - } - pending.push(schema); - } - json.additionalProperties = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - // Add required for keys with discrete values (enum, literal, etc.) - const keyValues = keyType._zod.values; - // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. - const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; - if (keyValues && !def.partial && !omittableOnInput) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json.required = validKeyValues.map(String); - } - } -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. - * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other - * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ -const UNREPRESENTABLE_DEFAULT = Symbol(); -function serializeDefaultValue(value, schema, ctx, json, params) { - let unrepresentable = false; - const serialized = JSON.stringify(value, (_, val) => { - if (typeof val !== "bigint") - return val; - unrepresentable = true; - return null; - }); - if (!unrepresentable) - return JSON.parse(serialized); - handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); - return UNREPRESENTABLE_DEFAULT; -} -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json.default = value; -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io !== "input") - return; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json._prefault = value; -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); - return; - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -// ==================== ALL PROCESSORS ==================== -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - // Registry case - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - // First pass: process all schemas to build the seen map - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - to_json_schema_process(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - // Update the context with external configuration - ctx.external = external; - // Second pass: emit each schema - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - assignProp(schemas, key, finalize(ctx, schema)); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - // Single schema case - const ctx = initializeContext({ ...params, processors: allProcessors }); - to_json_schema_process(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - - -const en_error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - mac: "MAC address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - credit_card: "credit card number", - jwt: "JWT", - template_literal: "input", - }; - // type names: missing keys = do not translate (use raw value via ?? fallback) - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN", - // All other type names omitted - they fall back to raw values via ?? operator - }; - function getTypeName(type, input) { - if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { - return String(input); - } - return TypeDictionary[type] ?? type; - } - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = getTypeName(issue.expected); - const receivedType = parsedType(issue.input); - const received = getTypeName(receivedType, issue.input); - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { - const opts = issue.options.map((o) => `'${o}'`).join(" | "); - return `Invalid discriminator value. Expected ${opts}`; - } - if (issue.inclusive === false) { - return "Invalid input: more than one option matched"; - } - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -/* export default */ function en() { - return { - localeError: en_error(), - }; -} - - - - -/* Prototypes that already carry the lazy helper methods. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -/* Helper methods live as non-enumerable lazy getters on the shared - * prototype instead of own properties on every instance. On first - * access the getter allocates the per-instance closure and caches it - * as a non-enumerable own property, so detached usage still works and - * the allocation only happens for methods actually touched. */ -function _lazyMethod(proto, key, make) { - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const value = make(this); - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - }, - }); -} -const classic_errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - const proto = Object.getPrototypeOf(inst); - if (_installedErrorProtos.has(proto)) - return; - _installedErrorProtos.add(proto); - _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); - _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); - _lazyMethod(proto, "addIssue", (self) => (issue) => { - self.issues.push(issue); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - _lazyMethod(proto, "addIssues", (self) => (issues) => { - self.issues.push(...issues); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - Object.defineProperty(proto, "isEmpty", { - configurable: true, - enumerable: false, - get() { - return this.issues.length === 0; - }, - }); -}; -const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); -const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - - - -const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); -const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); - -// Codec functions -const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); -const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); -const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); -const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); -const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - - - - - - - - -// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. -function _ensureDefaultLocale() { - if (!globalConfig.localeError) - core_config(en()); -} -// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first -function _ensureDefaultMemoizer() { - if (!globalConfig.memoizer) - core_config({ memoizer: memoizer() }); -} -const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - _ensureDefaultLocale(); - $ZodType.init(inst, def); - inst.def = def; - inst.type = def.type; - return inst; -}, { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return schemas_optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return schemas_optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return schemas_array(this); - }, - or(arg) { - return schemas_union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return schemas_default(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return schemas_catch(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(undefined).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn, ...args) { - return args.length === 0 ? fn(this) : fn(this, ...args); - }, - // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. - get "~standard"() { - return hide(this, "~standard", { - ...standardProps(this), - jsonSchema: { - input: createStandardJSONSchemaMethod(this, "input"), - output: createStandardJSONSchemaMethod(this, "output"), - }, - }); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, - parse: function _parse(data, params) { - return classic_parse_parse(this, data, params, { callee: _parse }); - }, - parseAsync: async function _parseAsync(data, params) { - return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); - }, - safeParse(data, params) { - return parse_safeParse(this, data, params); - }, - async safeParseAsync(data, params) { - return parse_safeParseAsync(this, data, params); - }, - // `spa` is an alias: same function object as `safeParseAsync`, as before. - get spa() { - return this?.safeParseAsync; - }, - set spa(value) { - util_own(this, "spa", value); - }, - encode: function _encode(data, params) { - return classic_parse_encode(this, data, params, { callee: _encode }); - }, - decode: function _decode(data, params) { - return classic_parse_decode(this, data, params, { callee: _decode }); - }, - encodeAsync: async function _encodeAsync(data, params) { - return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); - }, - decodeAsync: async function _decodeAsync(data, params) { - return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); - }, - safeEncode(data, params) { - return parse_safeEncode(this, data, params); - }, - safeDecode(data, params) { - return parse_safeDecode(this, data, params); - }, - async safeEncodeAsync(data, params) { - return parse_safeEncodeAsync(this, data, params); - }, - async safeDecodeAsync(data, params) { - return parse_safeDecodeAsync(this, data, params); - }, - toJSONSchema(params) { - return createToJSONSchemaMethod(this, {})(params); - }, - // Reads through to the registry on every access, so it must not cache. - get description() { - return globalRegistry.get(this)?.description; - }, - // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. - get _def() { - return this._zod.def; - }, -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; -}, { - regex(...args) { - return this.check(_regex(...args)); - }, - includes(...args) { - return this.check(_includes(...args)); - }, - startsWith(...args) { - return this.check(_startsWith(...args)); - }, - endsWith(...args) { - return this.check(_endsWith(...args)); - }, - min(...args) { - return this.check(_minLength(...args)); - }, - max(...args) { - return this.check(_maxLength(...args)); - }, - length(...args) { - return this.check(_length(...args)); - }, - nonempty(...args) { - return this.check(_minLength(1, ...args)); - }, - lowercase(params) { - return this.check(_lowercase(params)); - }, - uppercase(params) { - return this.check(_uppercase(params)); - }, - trim() { - return this.check(_trim()); - }, - normalize(...args) { - return this.check(_normalize(...args)); - }, - toLowerCase() { - return this.check(_toLowerCase()); - }, - toUpperCase() { - return this.check(_toUpperCase()); - }, - slugify() { - return this.check(_slugify()); - }, -}); -const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); -}, { - email(params) { - return this.check(_email(ZodEmail, params)); - }, - url(params) { - return this.check(_url(ZodURL, params)); - }, - jwt(params) { - return this.check(_jwt(ZodJWT, params)); - }, - emoji(params) { - return this.check(api_emoji(ZodEmoji, params)); - }, - guid(params) { - return this.check(_guid(ZodGUID, params)); - }, - uuid(params) { - return this.check(_uuid(ZodUUID, params)); - }, - uuidv4(params) { - return this.check(_uuidv4(ZodUUID, params)); - }, - uuidv6(params) { - return this.check(_uuidv6(ZodUUID, params)); - }, - uuidv7(params) { - return this.check(_uuidv7(ZodUUID, params)); - }, - nanoid(params) { - return this.check(_nanoid(ZodNanoID, params)); - }, - cuid(params) { - return this.check(_cuid(ZodCUID, params)); - }, - cuid2(params) { - return this.check(_cuid2(ZodCUID2, params)); - }, - ulid(params) { - return this.check(_ulid(ZodULID, params)); - }, - base64(params) { - return this.check(_base64(ZodBase64, params)); - }, - base64url(params) { - return this.check(_base64url(ZodBase64URL, params)); - }, - xid(params) { - return this.check(_xid(ZodXID, params)); - }, - ksuid(params) { - return this.check(_ksuid(ZodKSUID, params)); - }, - ipv4(params) { - return this.check(_ipv4(ZodIPv4, params)); - }, - ipv6(params) { - return this.check(_ipv6(ZodIPv6, params)); - }, - cidrv4(params) { - return this.check(_cidrv4(ZodCIDRv4, params)); - }, - cidrv6(params) { - return this.check(_cidrv6(ZodCIDRv6, params)); - }, - e164(params) { - return this.check(_e164(ZodE164, params)); - }, - datetime(params) { - return this.check(_isoDateTime(ZodISODateTime, params)); - }, - date(params) { - return this.check(_isoDate(ZodISODate, params)); - }, - time(params) { - return this.check(_isoTime(schemas_ZodISOTime, params)); - }, - duration(params) { - return this.check(_isoDuration(schemas_ZodISODuration, params)); - }, -}); -function schemas_string(params) { - return _string(ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_guid(params) { - return core._guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_uuid(params) { - return core._uuid(ZodUUID, params); -} -function uuidv4(params) { - return core._uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return core._uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function uuidv7(params) { - return core._uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return core._url(ZodURL, { - protocol: core.regexes.httpProtocol, - hostname: core.regexes.domain, - ...util.normalizeParams(params), - }); -} -const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_emoji(params) { - return core._emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_nanoid(params) { - return core._nanoid(ZodNanoID, params); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** - * Validates a CUID v1 string. - * - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. - * See https://github.com/paralleldrive/cuid. - */ -function schemas_cuid(params) { - return core._cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid2(params) { - return core._cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ulid(params) { - return core._ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_xid(params) { - return core._xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ksuid(params) { - return core._ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv4(params) { - return core._ipv4(ZodIPv4, params); -} -const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_mac(params) { - return core._mac(ZodMAC, params); -} -const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv6(params) { - return core._ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv4(params) { - return core._cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv6(params) { - return core._cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64(params) { - return core._base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64url(params) { - return core._base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_e164(params) { - return core._e164(ZodE164, params); -} -const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { - core.$ZodCreditCard.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_creditCard(params) { - return core._creditCard(ZodCreditCard, params); -} -const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return core._jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function stringFormat(format, fnOrRegex, _params = {}) { - return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function schemas_hostname(_params) { - return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); -} -function schemas_hex(_params) { - return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); -} -function schemas_hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = core.regexes[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return core._stringFormat(ZodCustomStringFormat, format, regex, params); -} -const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}, { - gt(value, params) { - return this.check(_gt(value, params)); - }, - gte(value, params) { - return this.check(_gte(value, params)); - }, - min(value, params) { - return this.check(_gte(value, params)); - }, - lt(value, params) { - return this.check(_lt(value, params)); - }, - lte(value, params) { - return this.check(_lte(value, params)); - }, - max(value, params) { - return this.check(_lte(value, params)); - }, - int(params) { - return this.check(schemas_int(params)); - }, - safe(params) { - return this.check(schemas_int(params)); - }, - positive(params) { - return this.check(_gt(0, params)); - }, - nonnegative(params) { - return this.check(_gte(0, params)); - }, - negative(params) { - return this.check(_lt(0, params)); - }, - nonpositive(params) { - return this.check(_lte(0, params)); - }, - multipleOf(value, params) { - return this.check(_multipleOf(value, params)); - }, - step(value, params) { - return this.check(_multipleOf(value, params)); - }, - finite() { - return this; - }, -}); -function schemas_number(params) { - return _number(ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function schemas_int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return core._float32(ZodNumberFormat, params); -} -function float64(params) { - return core._float64(ZodNumberFormat, params); -} -function int32(params) { - return core._int32(ZodNumberFormat, params); -} -function uint32(params) { - return core._uint32(ZodNumberFormat, params); -} -const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function schemas_boolean(params) { - return _boolean(ZodBoolean, params); -} -const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { - core.$ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}, { - gte(value, params) { - return this.check(checks.gte(value, params)); - }, - min(value, params) { - return this.check(checks.gte(value, params)); - }, - gt(value, params) { - return this.check(checks.gt(value, params)); - }, - lt(value, params) { - return this.check(checks.lt(value, params)); - }, - lte(value, params) { - return this.check(checks.lte(value, params)); - }, - max(value, params) { - return this.check(checks.lte(value, params)); - }, - positive(params) { - return this.check(checks.gt(BigInt(0), params)); - }, - negative(params) { - return this.check(checks.lt(BigInt(0), params)); - }, - nonpositive(params) { - return this.check(checks.lte(BigInt(0), params)); - }, - nonnegative(params) { - return this.check(checks.gte(BigInt(0), params)); - }, - multipleOf(value, params) { - return this.check(checks.multipleOf(value, params)); - }, -}))); -function schemas_bigint(params) { - return core._bigint(ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { - core.$ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); -}))); -function int64(params) { - return core._int64(ZodBigIntFormat, params); -} -function uint64(params) { - return core._uint64(ZodBigIntFormat, params); -} -const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { - core.$ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); -}))); -function symbol(params) { - return core._symbol(ZodSymbol, params); -} -const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { - core.$ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); -}))); -function schemas_undefined(params) { - return core._undefined(ZodUndefined, params); -} - -const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function schemas_null(params) { - return api_null(ZodNull, params); -} - -const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); -}); -function any() { - return _any(ZodAny); -} -const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); -}); -function unknown() { - return _unknown(ZodUnknown); -} -const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return _never(ZodNever, params); -} -const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { - core.$ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); -}))); -function schemas_void(params) { - return core._void(ZodVoid, params); -} - -const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { - core.$ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}))); -function schemas_date(params) { - return core._date(ZodDate, params); -} -const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; -}, { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - }, -}); -function schemas_array(element, params) { - return _array(ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return schemas_enum(Object.keys(shape)); -} -const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); -}, { - keyof() { - return schemas_enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall: catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: undefined }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - exactPartial(...args) { - return partial(ZodExactOptional, this, args[0], "exactPartial"); - }, - required(...args) { - return util_required(ZodNonOptional, this, args[0]); - }, -}); -function schemas_object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util.normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function schemas_union(options, params) { - return new ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - core.$ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}))); -/** Creates an exclusive union (XOR) where exactly one option must match. - * Unlike regular unions that succeed when any option matches, xor fails if - * zero or more than one option matches the input. */ -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new ZodDiscriminatedUnion({ - type: "union", - options: options, - discriminator, - ...normalizeParams(params), - }); -} -const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); -}, { - rest(rest) { - return this.clone({ - ...this._zod.def, - rest: rest, - }); - }, - partial() { - const def = this._zod.def; - // a refinement was authored against the full arity; partialing would run it on a shorter array - if (def.checks?.length) - throw new Error(".partial() cannot be used on tuple schemas containing refinements"); - return this.clone({ - ...def, - items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), - }); - }, -}))); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof core.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items: items, - rest, - ...util.normalizeParams(params), - }); -} -const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function schemas_record(keyType, valueType, params) { - // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() - if (!valueType || !valueType._zod) { - return new ZodRecord({ - type: "record", - keyType: schemas_string(), - valueType: keyType, - ...normalizeParams(valueType), - }); - } - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...util.normalizeParams(params), - partial: true, - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...util.normalizeParams(params), - }); -} -const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_set(valueType, params) { - return new ZodSet({ - type: "set", - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { - core.$ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); - inst.min = (size, params) => inst.check(core._minSize(size, params)); - inst.max = (size, params) => inst.check(core._maxSize(size, params)); - inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); -}))); -function schemas_file(params) { - return core._file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = inst); - // _issue.continue ??= true; - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function schemas_optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return schemas_optional(nullable(innerType)); -} -const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { - core.$ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), - }); -} - -const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { - core.$ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); -}))); -function nan(params) { - return core._nan(ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - core.$ZodCodec.init(inst, def); -}))); -function schemas_codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -function invertCodec(codec) { - const def = codec._zod.def; - return new ZodCodec({ - type: "pipe", - in: def.out, - out: def.in, - transform: def.reverseTransform, - reverseTransform: def.transform, - }); -} -const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { - ZodPipe.init(inst, def); - $ZodPreprocess.init(inst, def); -}); -const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { - core.$ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); -}))); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { - core.$ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function schemas_promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { - core.$ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); -}))); -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), - output: params?.output ?? unknown(), - }); -} - -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -// custom checks -function schemas_check(fn) { - const ch = new core.$ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return core._custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn, params) { - return _superRefine(fn, params); -} -// Re-export describe and meta from core -const schemas_describe = describe; -const schemas_meta = api_meta; -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util.normalizeParams(params), - }); - inst._zod.bag.Class = cls; - // Override check to emit invalid_type instead of custom - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...(inst._zod.def.path ?? [])], - }); - } - }; - return inst; -} - -// stringbool -const stringbool = (...args) => core._stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString, -}, ...args); -function schemas_json(params) { - const jsonSchema = lazy(() => { - return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -function preprocess(fn, schema) { - return new ZodPreprocess({ - type: "pipe", - in: transform(fn), - out: schema, - }); -} - - - - -function iso_datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -function iso_date(params) { - return _isoDate(ZodISODate, params); -} -function iso_time(params) { - return core._isoTime(ZodISOTime, params); -} -function iso_duration(params) { - return core._isoDuration(ZodISODuration, params); -} - -// Zod 3 compat layer - -/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ -const ZodIssueCode = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom", -}; - -/** @deprecated Use `z.config(params)` instead. */ -function setErrorMap(map) { - core.config({ - customError: map, - }); -} -/** @deprecated Use `z.config()` instead. */ -function getErrorMap() { - return core.config().customError; -} -/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ -var compat_ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); - - - -function coerce_string(params) { - return core._coercedString(schemas.ZodString, params); -} -function coerce_number(params) { - return _coercedNumber(ZodNumber, params); -} -function coerce_boolean(params) { - return core._coercedBoolean(schemas.ZodBoolean, params); -} -function coerce_bigint(params) { - return core._coercedBigint(schemas.ZodBigInt, params); -} -function coerce_date(params) { - return core._coercedDate(schemas.ZodDate, params); -} - - - -//#region src/constants.ts -const LATEST_PROTOCOL_VERSION = "2025-11-25"; -const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-06-18", - "2025-03-26", - "2024-11-05", - "2024-10-07" -]; -/** -* `_meta` key associating a message with a 2025-11-25 task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; -/** -* `_meta` key carrying the MCP protocol version governing a request. -* -* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. -*/ -const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; -/** -* `_meta` key identifying the client software making a request. -* -* Clients SHOULD include it on every request; the value is self-reported and -* intended for display, logging, and debugging — servers should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; -/** -* `_meta` key identifying the server software producing a response. -* -* Servers SHOULD include it on every response; the value is self-reported and -* intended for display, logging, and debugging — clients should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; -/** -* `_meta` key carrying the client's capabilities for a request. -* -* Capabilities are declared per request rather than once at initialization; -* servers must not infer capabilities from prior requests. -*/ -const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; -/** -* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request -* that opened the stream a notification was delivered on. -* -* Stamped by the server on every notification delivered via a -* `subscriptions/listen` stream (including the leading -* `notifications/subscriptions/acknowledged`); on stdio, where all messages -* share one channel, clients use it to correlate notifications with their -* originating subscription. The value is the listen request's JSON-RPC ID -* verbatim. -*/ -const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; -/** -* `_meta` key carrying the desired log level for a request. -* -* When absent, the server must not send `notifications/message` notifications -* for the request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. -*/ -const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; -/** -* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `traceparent` header format, -* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. -* -* @see https://www.w3.org/TR/trace-context/#traceparent-header -*/ -const TRACEPARENT_META_KEY = "traceparent"; -/** -* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `tracestate` header format, -* e.g. `vendor1=value1,vendor2=value2`. -* -* @see https://www.w3.org/TR/trace-context/#tracestate-header -*/ -const TRACESTATE_META_KEY = "tracestate"; -/** -* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C Baggage header format, -* e.g. `userId=alice,serverRegion=us-east-1`. -* -* @see https://www.w3.org/TR/baggage/ -*/ -const BAGGAGE_META_KEY = "baggage"; -const JSONRPC_VERSION = "2.0"; -const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); -const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); -const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); -const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); -const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); - -//#endregion -//#region src/schemas.ts -const JSONValueSchema = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema), - schemas_array(JSONValueSchema) -])); -const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); -const JSONArraySchema = schemas_array(JSONValueSchema); -/** -* A progress token, used to associate progress notifications with the original request. -*/ -const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* An opaque token used to represent a cursor for pagination. -*/ -const CursorSchema = schemas_string(); -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); -/** -* Metadata for associating messages with a task. -* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); -const RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -/** -* Common params for any request. -*/ -const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -/** -* Common params for any task-augmented request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); -const RequestSchema = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -const NotificationSchema = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema.loose().optional() -}); -/** -* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). -* Loose — implementation-specific keys pass through. -* -* The serverInfo key identifies the server software producing the response -* (servers SHOULD include it on every response; the value is self-reported -* and intended for display, logging, and debugging). The getter defers the -* `ImplementationSchema` reference, which is declared later in this file. -*/ -const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { - return ImplementationSchema.optional().catch(void 0); -} }); -const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); -/** -* A uniquely identifying ID for a request in JSON-RPC. -*/ -const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* A request that expects a response. -*/ -const JSONRPCRequestSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}).strict(); -/** -* A notification which does not expect a response. -*/ -const JSONRPCNotificationSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}).strict(); -/** -* A successful (non-error) response to a request. -*/ -const JSONRPCResultResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -/** -* A response to a request that indicates an error occurred. -*/ -const JSONRPCErrorResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: schemas_object({ - code: schemas_number().int(), - message: schemas_string(), - data: unknown().optional() - }) -}).strict(); -const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -/** -* A response that indicates success but carries no data. -*/ -const EmptyResultSchema = ResultSchema.strict(); -const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: schemas_string().optional() -}); -/** -* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. -* -* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. -* -* This notification indicates that the result will be unused, so any associated processing SHOULD cease. -* -* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. -*/ -const CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema -}); -/** -* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. -*/ -const IconSchema = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() -}); -/** -* Base schema to add `icons` property. -* -*/ -const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); -/** -* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. -*/ -const BaseMetadataSchema = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() -}); -/** -* Describes the name and version of an MCP implementation. -*/ -const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() -}); -const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); -const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; -}, intersection(schemas_object({ - form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() -}), JSONObjectSchema.optional())); -/** -* Task capabilities for clients, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ClientTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() - }).optional() -}); -/** -* Task capabilities for servers, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ServerTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() -}); -/** -* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. -*/ -const ClientCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - sampling: schemas_object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }).optional(), - elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** -* This request is sent from the client to the server when it first connects, asking it to begin initialization. -*/ -const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema -}); -/** -* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. -*/ -const ServerCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -/** -* After receiving an initialize request from the client, the server sends this response. -*/ -const InitializeResultSchema = ResultSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: schemas_string().optional() -}); -/** -* This notification is sent from the client to the server after initialization has finished. -*/ -const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() -}); -/** -* A request from the client asking the server to advertise its supported protocol -* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers -* MUST implement `server/discover`. Clients MAY call it but are not required to — -* version negotiation can also happen inline via the per-request `_meta` envelope. -*/ -const DiscoverRequestSchema = RequestSchema.extend({ - method: literal("server/discover"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The result returned by the server for a `server/discover` request. -*/ -const DiscoverResultSchema = ResultSchema.extend({ - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilitiesSchema, - instructions: schemas_string().optional() -}); -/** -* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. -*/ -const PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() -}); -const ProgressSchema = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) -}); -const ProgressNotificationParamsSchema = schemas_object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); -/** -* An out-of-band notification used to inform the receiver of a progress update for a long-running request. -* -* @category notifications/progress -*/ -const ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema -}); -const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); -const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); -const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); -/** -* The contents of a specific resource or sub-resource. -*/ -const ResourceContentsSchema = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); -/** -* A Zod schema for validating Base64 strings that is more performant and -* robust for very large inputs than the default regex-based check. It avoids -* stack overflows by using the native `atob` function for validation. -*/ -const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } -}, { message: "Invalid Base64 string" }); -const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); -/** -* The sender or recipient of messages and data in a conversation. -*/ -const RoleSchema = schemas_enum(["user", "assistant"]); -/** -* Optional annotations providing clients additional context about a resource. -*/ -const AnnotationsSchema = schemas_object({ - audience: schemas_array(RoleSchema).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() -}); -/** -* A known resource that the server is capable of reading. -*/ -const ResourceSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* A template description for resources available on the server. -*/ -const ResourceTemplateSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of resources the server has. -*/ -const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); -/** -* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. -*/ -const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); -/** -* Sent from the client to request a list of resource templates the server has. -*/ -const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); -/** -* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. -*/ -const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); -const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); -/** -* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. -*/ -const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to the server, to read a specific resource URI. -*/ -const ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema -}); -/** -* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. -*/ -const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); -/** -* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() -}); -const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. -*/ -const SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema -}); -const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema -}); -/** -* The set of notification types a client opts in to on a `subscriptions/listen` -* request. Each type is opt-in; the server MUST NOT send a notification type -* the client has not explicitly requested here. -*/ -const SubscriptionFilterSchema = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() -}); -const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent from the client to open a long-lived channel for receiving notifications -* outside the context of a specific request (protocol revision 2026-07-28). -* Replaces the previous HTTP GET endpoint and `resources/subscribe`. -*/ -const SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: literal("subscriptions/listen"), - params: SubscriptionsListenRequestParamsSchema -}); -const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent by the server as the first message on a `subscriptions/listen` stream -* to acknowledge that the subscription has been established and report which -* notification types it agreed to honor (protocol revision 2026-07-28). -*/ -const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/subscriptions/acknowledged"), - params: SubscriptionsAcknowledgedNotificationParamsSchema -}); -/** -* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's -* JSON-RPC ID under the canonical subscription-id key (mirroring the same key -* on every notification delivered on the stream). Extends -* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed -* here too. -*/ -const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); -/** -* The response to a `subscriptions/listen` request, signalling that the -* subscription has ended gracefully (for example, during server shutdown). -* Because the listen stream is long-lived, this result is sent only when the -* server tears the subscription down; an abrupt transport close carries no -* response. The result body is otherwise empty. -*/ -const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); -/** -* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. -*/ -const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); -/** -* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema -}); -/** -* Describes an argument that a prompt can accept. -*/ -const PromptArgumentSchema = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) -}); -/** -* A prompt or prompt template that the server offers. -*/ -const PromptSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema)), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of prompts and prompt templates the server has. -*/ -const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); -/** -* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. -*/ -const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); -/** -* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. -*/ -const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() -}); -/** -* Used by the client to get a prompt provided by the server. -*/ -const GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema -}); -/** -* Text provided to or from an LLM. -*/ -const TextContentSchema = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* An image provided to or from an LLM. -*/ -const ImageContentSchema = schemas_object({ - type: literal("image"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Audio content provided to or from an LLM. -*/ -const AudioContentSchema = schemas_object({ - type: literal("audio"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A tool call request from an assistant (LLM). -* Represents the assistant's request to use a tool. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolUseContentSchema = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* The contents of a resource, embedded into a prompt or tool call result. -*/ -const EmbeddedResourceSchema = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A resource that the server is capable of reading, included in a prompt or tool call result. -* -* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. -*/ -const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); -/** -* A content block that can be used in prompts and tool results. -*/ -const ContentBlockSchema = schemas_union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** -* Describes a message returned as part of a prompt. -*/ -const PromptMessageSchema = schemas_object({ - role: RoleSchema, - content: ContentBlockSchema -}); -/** -* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. -*/ -const GetPromptResultSchema = ResultSchema.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema) -}); -/** -* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Additional properties describing a `Tool` to clients. -* -* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. -* They are not guaranteed to provide a faithful description of -* tool behavior (including descriptive properties like `title`). -* -* Clients should never make tool use decisions based on `ToolAnnotations` -* received from untrusted servers. -*/ -const ToolAnnotationsSchema = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() -}); -/** -* Execution-related properties for a tool. -*/ -const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" -]).optional() }); -/** -* Definition for a tool the client can call. -*/ -const ToolSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the client to request a list of tools the server has. -*/ -const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); -/** -* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. -*/ -const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); -/** -* The server's response to a tool call. -*/ -const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ - content: schemas_array(ContentBlockSchema).default([]), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() -}); -/** -* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. -*/ -const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); -/** -* Parameters for a `tools/call` request. -*/ -const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Used by the client to invoke a tool provided by the server. -*/ -const CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema -}); -/** -* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Base schema for list changed subscription options (without callback). -* Used internally for Zod validation of `autoRefresh` and `debounceMs`. -*/ -const ListChangedOptionsBaseSchema = schemas_object({ - autoRefresh: schemas_boolean().default(true), - debounceMs: schemas_number().int().nonnegative().default(300) -}); -/** -* The severity of a log message. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingLevelSchema = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" -]); -/** -* Parameters for a `logging/setLevel` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); -/** -* A request from the client to the server, to enable or adjust logging. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema -}); -/** -* Parameters for a `notifications/message` notification. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: schemas_string().optional(), - data: unknown() -}); -/** -* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema -}); -/** -* Hints to use for model selection. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); -/** -* The server's preferences for model selection, requested of the client during sampling. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelPreferencesSchema = schemas_object({ - hints: schemas_array(ModelHintSchema).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() -}); -/** -* Controls tool usage behavior in sampling requests. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" -]).optional() }); -/** -* The result of a tool execution, provided by the user (server). -* Represents the outcome of invoking a tool requested via `ToolUseContent`. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolResultContentSchema = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Basic content types for sampling responses (without tool use). -* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingContentSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema -]); -/** -* Content block types allowed in sampling messages. -* This includes text, image, audio, tool use requests, and tool results. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** -* Describes a message issued to or received from an LLM API. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageSchema = schemas_object({ - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Parameters for a `sampling/createMessage` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - messages: schemas_array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema.optional(), - tools: schemas_array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); -/** -* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema -}); -/** -* The client's response to a `sampling/create_message` request from the server. -* This is the backwards-compatible version that returns single content (no arrays). -* Used when the request does not include tools. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema, - content: SamplingContentSchema -}); -/** -* The client's response to a `sampling/create_message` request when tools were provided. -* This version supports array content for tool use flows. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) -}); -/** -* Primitive schema definition for boolean fields. -*/ -const BooleanSchemaSchema = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() -}); -/** -* Primitive schema definition for string fields. -*/ -const StringSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() -}); -/** -* Primitive schema definition for number fields. -*/ -const NumberSchemaSchema = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() -}); -/** -* Schema for single-selection enumeration without display titles for options. -*/ -const UntitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() -}); -/** -* Schema for single-selection enumeration with display titles for each option. -*/ -const TitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() -}); -/** -* Use {@linkcode TitledSingleSelectEnumSchema} instead. -* This interface will be removed in a future version. -*/ -const LegacyTitledEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() -}); -const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** -* Schema for multiple-selection enumeration without display titles for options. -*/ -const UntitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Schema for multiple-selection enumeration with display titles for each option. -*/ -const TitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Combined schema for multiple-selection enumeration -*/ -const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** -* Primitive schema definition for enum fields. -*/ -const EnumSchemaSchema = schemas_union([ - LegacyTitledEnumSchemaSchema, - SingleSelectEnumSchemaSchema, - MultiSelectEnumSchemaSchema -]); -/** -* Union of all primitive schema definitions. -*/ -const PrimitiveSchemaDefinitionSchema = schemas_union([ - EnumSchemaSchema, - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema -]); -/** -* Parameters for an `elicitation/create` request for form-based elicitation. -*/ -const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) -}); -/** -* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. -*/ -const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() -}); -/** -* The parameters for a request to elicit additional information from the user via the client. -*/ -const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** -* A request from the server to elicit user input via the client. -* The client should present the message and form fields to the user (form mode) -* or navigate to a URL (URL mode). -*/ -const ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema -}); -/** -* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); -/** -* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema -}); -/** -* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. -*/ -const ElicitResultSchema = ResultSchema.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) -}); -/** -* A reference to a resource or resource template definition. -*/ -const ResourceTemplateReferenceSchema = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() -}); -/** -* Identifies a prompt. -*/ -const PromptReferenceSchema = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() -}); -/** -* Parameters for a {@linkcode CompleteRequest | completion/complete} request. -*/ -const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() -}); -/** -* A request from the client to the server, to ask for completion options. -*/ -const CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema -}); -/** -* The server's response to a {@linkcode CompleteRequest | completion/complete} request -*/ -const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) -}) }); -/** -* Represents a root directory or file that the server can operate on. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootSchema = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the server to request a list of root URIs from the client. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The client's response to a `roots/list` request from the server. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); -/** -* A notification from the client to the server, informing it that the list of roots has changed. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Task creation parameters, used to ask that the server create a task to represent a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskCreationParamsSchema = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() -}); -/** -* The status of a task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusSchema = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" -]); -/** -* A pollable state object associated with a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskSchema = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) -}); -/** -* Result returned when a task is created, containing the task data wrapped in a `task` field. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); -/** -* Parameters for task status notification. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -/** -* A notification sent when a task's status changes. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema -}); -/** -* A request to get the state of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode GetTaskRequest | tasks/get} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -/** -* A request to get the result of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a `tasks/result` request. -* The structure matches the result type of the original request. -* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. -* -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadResultSchema = ResultSchema.loose(); -/** -* A request to list tasks. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); -/** -* The response to a {@linkcode ListTasksRequest | tasks/list} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); -/** -* A request to cancel a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -const ClientRequestSchema = schemas_union([ - PingRequestSchema, - auth_CUe6YdwF_InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -const ClientNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - auth_CUe6YdwF_InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -const ClientResultSchema = schemas_union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema -]); -const ServerRequestSchema = schemas_union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema -]); -const ServerNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema -]); -const ServerResultSchema = schemas_union([ - EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - auth_CUe6YdwF_CallToolResultSchema, - ListToolsResultSchema, - SubscriptionsListenResultSchema -]); - -//#endregion -//#region src/auth.ts -/** -* Reusable URL validation that disallows `javascript:` scheme -*/ -const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: "URL must be parseable", - fatal: true - }); - return NEVER; - } -}).refine((url) => { - const u = new URL(url); - return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; -}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); -/** -* RFC 9728 OAuth Protected Resource Metadata -*/ -const OAuthProtectedResourceMetadataSchema = looseObject({ - resource: schemas_string().url(), - authorization_servers: schemas_array(SafeUrlSchema).optional(), - jwks_uri: schemas_string().url().optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - bearer_methods_supported: schemas_array(schemas_string()).optional(), - resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - resource_name: schemas_string().optional(), - resource_documentation: schemas_string().optional(), - resource_policy_uri: schemas_string().url().optional(), - resource_tos_uri: schemas_string().url().optional(), - tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), - authorization_details_types_supported: schemas_array(schemas_string()).optional(), - dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - dpop_bound_access_tokens_required: schemas_boolean().optional() -}); -/** -* RFC 8414 OAuth 2.0 Authorization Server Metadata -*/ -const OAuthMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint: schemas_string().optional(), - introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - code_challenge_methods_supported: schemas_array(schemas_string()).optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery 1.0 Provider Metadata -* -* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata -*/ -const OpenIdProviderMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - acr_values_supported: schemas_array(schemas_string()).optional(), - subject_types_supported: schemas_array(schemas_string()), - id_token_signing_alg_values_supported: schemas_array(schemas_string()), - id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - display_values_supported: schemas_array(schemas_string()).optional(), - claim_types_supported: schemas_array(schemas_string()).optional(), - claims_supported: schemas_array(schemas_string()).optional(), - service_documentation: schemas_string().optional(), - claims_locales_supported: schemas_array(schemas_string()).optional(), - ui_locales_supported: schemas_array(schemas_string()).optional(), - claims_parameter_supported: schemas_boolean().optional(), - request_parameter_supported: schemas_boolean().optional(), - request_uri_parameter_supported: schemas_boolean().optional(), - require_request_uri_registration: schemas_boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery metadata that may include OAuth 2.0 fields -* This schema represents the real-world scenario where OIDC providers -* return a mix of OpenID Connect and OAuth 2.0 metadata fields -*/ -const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape -}); -/** -* OAuth 2.1 token response -*/ -const OAuthTokensSchema = schemas_object({ - access_token: schemas_string(), - id_token: schemas_string().optional(), - token_type: schemas_string(), - expires_in: coerce_number().optional(), - scope: schemas_string().optional(), - refresh_token: schemas_string().optional() -}).strip(); -/** -* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. -* -* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when -* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, -* so strict checking rejects conformant IdPs. -*/ -const IdJagTokenExchangeResponseSchema = schemas_object({ - issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), - access_token: schemas_string(), - token_type: schemas_string().optional(), - expires_in: schemas_number().optional(), - scope: schemas_string().optional() -}).strip(); -/** -* OAuth 2.1 error response -*/ -const OAuthErrorResponseSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional(), - error_uri: schemas_string().optional() -}); -/** -* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` -*/ -const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata -*/ -const OAuthClientMetadataSchema = schemas_object({ - redirect_uris: schemas_array(SafeUrlSchema), - token_endpoint_auth_method: schemas_string().optional(), - grant_types: schemas_array(schemas_string()).optional(), - response_types: schemas_array(schemas_string()).optional(), - application_type: schemas_string().optional(), - client_name: schemas_string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: schemas_string().optional(), - contacts: schemas_array(schemas_string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: schemas_string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: any().optional(), - software_id: schemas_string().optional(), - software_version: schemas_string().optional(), - software_statement: schemas_string().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration client information -*/ -const OAuthClientInformationSchema = schemas_object({ - client_id: schemas_string(), - client_secret: schemas_string().optional(), - client_id_issued_at: schemas_number().optional(), - client_secret_expires_at: schemas_number().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) -*/ -const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration error response -*/ -const OAuthClientRegistrationErrorSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional() -}).strip(); -/** -* RFC 7009 OAuth 2.0 Token Revocation request -*/ -const OAuthTokenRevocationRequestSchema = schemas_object({ - token: schemas_string(), - token_type_hint: schemas_string().optional() -}).strip(); - -//#endregion - -//# sourceMappingURL=auth-CUe6YdwF.mjs.map - - - - - - - - -//#region ../core-internal/src/errors/crossBundleBrand.ts -/** -* Cross-bundle `instanceof` support for the SDK error classes. -* -* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their -* own copy of `core-internal`, so an error constructed by one package fails a -* prototype-identity `instanceof` against the same class re-exported by the other — -* exactly the check a dual-role process (gateway, host, in-process test) writes. -* -* Instead of prototype identity, branded classes stamp every instance with the brand -* strings of its class chain under a registry symbol (`Symbol.for`, shared across -* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the -* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior -* is unchanged for anything unbranded. -* -* A class participates by defining an **own** `mcpBrand` static (via a `static {}` -* block, so nothing reaches the declaration files — a declared `protected static` -* field would make the constructor types nominally incompatible across the bundled -* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as -* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand -* keep plain prototype semantics — a foreign base-class instance never satisfies -* `instanceof UserSubclass`. -* -* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core -* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), -* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios -* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a -* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 -* (Symbol.hasInstance on every schema class for cross-version interop). -* -* Contract notes: -* - Participation criterion: **every error class exported from a public package that -* callers are documented to `instanceof` must be branded.** The per-package -* errorBrandConformance tests walk the export surfaces and fail naming any -* exported Error subclass that has not opted in. -* - Brands assert **identity, not shape**: brand strings are version-less, so an -* instance from one SDK version matches the class of another. Members added to a -* branded class in a later version may be absent on a matched instance — read -* fields defensively, and treat branded classes as additive-only. The escape -* hatch when a release must break a branded class's read contract: change that -* class's brand string in the same release, which cleanly severs cross-version -* matching for that class. The per-package brand pins make the rename -* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each -* package's errorBrandConformance test pins its package-local ones. -* - Cross-bundle matching requires **both** copies to be at or after the release -* that introduced branding; against an older copy, behavior degrades to plain -* prototype `instanceof` in both directions. -* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would -* break the brand statics; default esbuild/webpack/terser settings do not. -*/ -/** Registry symbol — identical across bundled copies and realms. */ -const BRANDS = Symbol.for("mcp.sdk.errorBrands"); -/** -* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an -* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — -* subclasses inherit the stamping without touching their constructors. -* -* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would -* satisfy `instanceof` while lacking the prototype members (getters like `.status`) -* that callers reach for after the check. -*/ -function stampErrorBrands(instance, ctor) { - const brands = /* @__PURE__ */ new Set(); - let current = ctor; - while (typeof current === "function") { - const brand = current.mcpBrand; - if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); - current = Object.getPrototypeOf(current); - } - if (brands.size === 0) return; - Object.defineProperty(instance, BRANDS, { - value: brands, - enumerable: false, - configurable: true - }); -} -/** -* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the -* value carries the **own** brand of the class being tested against (cross-bundle -* path), falling back to ordinary prototype-based `instanceof` otherwise. -*/ -function brandedHasInstance(cls, value) { - try { - if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { - const carried = value[BRANDS]; - if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; - } - } catch {} - return Function.prototype[Symbol.hasInstance].call(cls, value); -} - -//#endregion -//#region ../core-internal/src/auth/errors.ts -/** -* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} -* and extensions. -*/ -let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { - /** - * The request is missing a required parameter, includes an invalid parameter value, - * includes a parameter more than once, or is otherwise malformed. - */ - OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; - /** - * Client authentication failed (e.g., unknown client, no client authentication included, - * or unsupported authentication method). - */ - OAuthErrorCode$1["InvalidClient"] = "invalid_client"; - /** - * The provided authorization grant or refresh token is invalid, expired, revoked, - * does not match the redirection URI used in the authorization request, or was issued to another client. - */ - OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; - /** - * The authenticated client is not authorized to use this authorization grant type. - */ - OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; - /** - * The authorization grant type is not supported by the authorization server. - */ - OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; - /** - * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. - */ - OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; - /** - * The resource owner or authorization server denied the request. - */ - OAuthErrorCode$1["AccessDenied"] = "access_denied"; - /** - * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. - */ - OAuthErrorCode$1["ServerError"] = "server_error"; - /** - * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. - */ - OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; - /** - * The authorization server does not support obtaining an authorization code using this method. - */ - OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; - /** - * The authorization server does not support the requested token type. - */ - OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; - /** - * The access token provided is expired, revoked, malformed, or invalid for other reasons. - */ - OAuthErrorCode$1["InvalidToken"] = "invalid_token"; - /** - * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) - */ - OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; - /** - * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) - */ - OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; - /** - * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) - */ - OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; - /** - * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) - */ - OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; - /** - * The request requires higher privileges than provided by the access token. - */ - OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; - /** - * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) - */ - OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; - return OAuthErrorCode$1; -}({}))); -/** -* OAuth error class for all OAuth-related errors. -*/ -var src_CX2iR2pK_OAuthError = class OAuthError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, errorUri) { - super(message); - this.code = code; - this.errorUri = errorUri; - this.name = "OAuthError"; - stampErrorBrands(this, new.target); - } - /** - * Converts the error to a standard OAuth error response object. - */ - toResponseObject() { - const response = { - error: this.code, - error_description: this.message - }; - if (this.errorUri) response.error_uri = this.errorUri; - return response; - } - /** - * Creates an {@linkcode OAuthError} from an OAuth error response. - */ - static fromResponse(response) { - return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); - } -}; - -//#endregion -//#region ../core-internal/src/errors/sdkErrors.ts -/** -* Error codes for SDK errors (local errors that never cross the wire). -* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses -* descriptive string values for better developer experience. -* -* These errors are thrown locally by the SDK and are never serialized as -* JSON-RPC error responses. -*/ -let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { - /** Transport is not connected */ - SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; - /** Transport is already connected */ - SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; - /** Protocol is not initialized */ - SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; - /** Required capability is not supported by the remote side */ - SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; - /** Request timed out waiting for response */ - SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; - /** Connection was closed */ - SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; - /** Failed to send message */ - SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; - /** Response result failed local schema validation */ - SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; - /** - * The response carried a `resultType` discriminator (protocol revision - * 2026-07-28) naming a result kind this client cannot consume yet, e.g. - * `input_required`. The kind is carried in `data.resultType`. - */ - SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; - /** - * The multi-round-trip auto-fulfilment driver exhausted its round cap - * (`inputRequired.maxRounds`) without the server returning a complete - * result. `data.rounds` carries the cap that was hit and - * `data.lastResult` carries the last `input_required` payload received - * (`{ inputRequests, requestState? }`), so callers can inspect or resume - * the flow manually. - */ - SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; - /** - * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / - * `listResources()` / `listResourceTemplates()` walk hit the - * `ClientOptions.listMaxPages` cap without the server's pagination - * converging. `data.method` carries the list verb and - * `data.listMaxPages` the cap that was hit; raise the cap or fall back to - * explicit per-page `{ cursor }` calls. - */ - SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; - /** - * The spec method being sent does not exist on the negotiated protocol - * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or - * `server/discover` toward a 2025-era peer). Raised locally, before - * anything reaches the transport. The method and era are carried in - * `data.method` / `data.era`. - */ - SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; - /** - * Protocol-era negotiation at connect time failed without producing either a - * usable modern (2026-07-28+) era or a definitive legacy fallback signal — - * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a - * network failure, or the server answered the probe with a 5xx (a typed - * connect error, never an era verdict). - * - * Negotiation-phase only: this code is never used once an era is - * established. Auth walls never carry it: a 401/403 rejecting the probe - * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} - * instead, so era-recovery flows keyed on this code (e.g. cached-verdict - * gateways) can never persist a verdict for an unauthorized exchange. - */ - SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; - SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; - /** - * HTTP 401 authentication failure: the transport's re-auth retry still got - * 401 (`Server returned 401 after re-authentication`), or the version - * negotiation probe was rejected 401 with no `authProvider` configured - * (`Version negotiation failed: the server requires authorization (HTTP 401)`). - * Carried on an {@linkcode SdkHttpError} with `status: 401`. - */ - SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; - /** - * HTTP 403 denial: the step-up re-authorization retry limit was reached, - * or the version negotiation probe was rejected 403 - * (`Version negotiation failed: the server denied access (HTTP 403)`). - * Carried on an {@linkcode SdkHttpError} with `status: 403`. - */ - SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; - SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; - SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; - SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; - return SdkErrorCode$1; -}({}); -/** -* SDK errors are local errors that never cross the wire. -* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors -* that are serialized and sent as error responses. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" -* try { -* // Throwing an SDK error -* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); -* } catch (error) { -* // Checking error type by code -* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { -* // Handle timeout -* } -* } -* ``` -*/ -var src_CX2iR2pK_SdkError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "SdkError"; - stampErrorBrands(this, new.target); - } -}; -/** -* An {@linkcode SdkError} subclass for HTTP transport failures. -* -* Thrown by the streamable HTTP transport when the server responds with a -* non-OK status code. Narrows {@linkcode SdkError.data | data} to -* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status -* without unsafe casting. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" -* if (error instanceof SdkHttpError) { -* console.log(error.status); // number -* console.log(error.statusText); // string | undefined -* } -* ``` -*/ -var SdkHttpError = class extends src_CX2iR2pK_SdkError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); - } - constructor(code, message, data) { - super(code, message, data); - this.name = "SdkHttpError"; - } - get status() { - return this.data.status; - } - get statusText() { - return this.data.statusText; - } -}; - -//#endregion -//#region ../core-internal/src/shared/authUtils.ts -/** -* Utilities for handling OAuth resource URIs. -*/ -/** -* Converts a server URL to a resource URL by removing the fragment. -* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} -* states that resource URIs "MUST NOT include a fragment component". -* Keeps everything else unchanged (scheme, domain, port, path, query). -*/ -function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); - resourceURL.hash = ""; - return resourceURL; -} -/** -* Checks if a requested resource URL matches a configured resource URL. -* A requested resource matches if it has the same scheme, domain, port, -* and its path starts with the configured resource's path. -* -* @param options - The options object -* @param options.requestedResource - The resource URL being requested -* @param options.configuredResource - The resource URL that has been configured -* @returns true if the requested resource matches the configured resource, false otherwise -*/ -function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); - if (requested.origin !== configured.origin) return false; - if (requested.pathname.length < configured.pathname.length) return false; - const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; - const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; - return requestedPath.startsWith(configuredPath); -} - -//#endregion -//#region ../core-internal/src/shared/clientCapabilityRequirements.ts -/** -* Inbound request methods whose processing structurally requires a client -* capability, keyed by method, valued by the capabilities required. -* -* Currently empty: none of the request methods served on the 2026-07-28 -* registry unconditionally requires a client capability. Entries appear here -* when such methods exist — for example requests whose handling embeds -* elicitation or sampling input requests (the input-request engine), or -* opt-in subscription delivery. Handler-conditional requirements (a specific -* tool that needs sampling) are not expressible as a static method table and -* are enforced at the point the requirement arises instead. -*/ -const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); -/** -* The client capabilities a request method structurally requires, or -* `undefined` when the method has no static requirement. -*/ -function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { - return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; -} -function isPlainObject$7(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Whether a required nested member counts as declared even though it is not -* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at -* all) is read as form support — the pre-mode (2025) meaning of a bare -* declaration — so an `elicitation.form` requirement treats it as satisfied. -* Declaring any mode explicitly (for example `elicitation: { url: {} }`) -* removes the implication. -*/ -function isImpliedCapabilityMember(capability, member, declaredValue) { - return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; -} -/** -* The client capabilities an embedded multi-round-trip input request requires -* (call site 2 — the outbound input-request leg): a server MUST NOT send an -* `inputRequests` kind the request's declared client capabilities do not -* cover. Returns `undefined` for entries whose method is not one of the -* embedded input-request kinds (those are a server bug handled separately, -* not a capability question). -* -* The requirement is mode-aware where the capability is: URL-mode elicitation -* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires -* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a -* mode the client did not declare); sampling with `tools`/`toolChoice` -* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies -* the form requirement — see {@linkcode missingClientCapabilities}. -*/ -function requiredClientCapabilitiesForInputRequest(entry) { - switch (entry.method) { - case "elicitation/create": - if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; - return { elicitation: { form: {} } }; - case "sampling/createMessage": { - const params = entry.params; - if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; - return { sampling: {} }; - } - case "roots/list": return { roots: {} }; - default: return; - } -} -/** -* Computes the subset of `required` client capabilities the client did not -* declare. Returns `undefined` when every required capability is declared; -* otherwise returns an object in the `ClientCapabilities` shape containing -* exactly the missing capabilities (suitable for -* `data.requiredCapabilities` on the `-32021` error). -* -* A capability counts as declared when its top-level key is present on the -* declared capabilities; when the requirement names nested members (for -* example `elicitation: { url: {} }`), each named member must also be present -* under the declared capability. One lenient reading applies: a bare -* `elicitation: {}` declaration (no mode sub-capability at all) counts as -* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare -* declaration. An absent or empty `declared` value means -* nothing is declared — every required capability is missing (the structural -* clean-refusal posture for sessions with no per-request capability view). -*/ -function src_CX2iR2pK_missingClientCapabilities(required, declared) { - const missing = {}; - for (const [capability, requirement] of Object.entries(required)) { - if (requirement === void 0) continue; - const declaredValue = declared === void 0 ? void 0 : declared[capability]; - if (declaredValue === void 0) { - missing[capability] = requirement; - continue; - } - if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { - const missingMembers = {}; - for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; - if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; - } - } - return Object.keys(missing).length > 0 ? missing : void 0; -} - -//#endregion -//#region ../core-internal/src/shared/protocolEras.ts -/** -* The first protocol revision of the modern (2026-07-28) era. Revision identifiers -* are ISO dates, so lexicographic comparison orders them chronologically. -*/ -const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; -/** -* Modern-era protocol revisions this SDK can negotiate via `server/discover`. -* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy -* `initialize` list), so adding a revision here can never leak a modern version -* string into a 2025-era handshake. Internal — not part of the public API surface. -*/ -const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); -/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ -function isModernProtocolVersion(version) { - return version >= FIRST_MODERN_PROTOCOL_VERSION; -} -/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ -function legacyProtocolVersions(versions) { - return versions.filter((version) => !isModernProtocolVersion(version)); -} -/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ -function modernProtocolVersions(versions) { - return versions.filter((version) => isModernProtocolVersion(version)); -} - -//#endregion -//#region ../core-internal/src/wire/textFallback.ts -/** -* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH -* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` -* is a non-object value (array/primitive/`null`) and the handler authored no -* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. -* Object-shaped (or absent) `structuredContent` returns the same reference. -* -* Leaf module: imported by both era codec modules, so it must NOT import from -* `./codec.js` (which value-imports the rev codecs at top level — that would -* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec -* module first). -*/ -function appendTextFallbackForNonObject(result) { - const sc = result.structuredContent; - if (sc === void 0) return result; - if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; - if (result.content?.some((c) => c.type === "text") ?? false) return result; - return { - ...result, - content: [...result.content ?? [], { - type: "text", - text: JSON.stringify(sc) - }] - }; -} - -//#endregion -//#region ../core-internal/src/wire/resultFamilies.ts -/** -* Result-family keys that must never default into a `{content: []}` tools/call -* success. Shared by the 2025 wire-seam schema and server normalization. -* Leaf module (like `textFallback.ts`): imported by registry/server paths, so -* it must NOT import from `./codec.js` — that would close a runtime cycle. -*/ -const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ - "task", - "inputRequests", - "requestState" -]; -/** -* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and -* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. -*/ -function normalizeContentlessToolResult(value) { - if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; - return { - ...value, - content: [] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts -/** -* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from -* the public/neutral types/schemas.ts. The neutral layer is the public-API -* superset and is free to evolve (e.g., SEP-2106 widening); this file is the -* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. -* -* This is the era's complete frozen wire-parse contract — both the 2025-only -* delta (the deprecated task family, the era role unions) AND frozen copies of -* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, -* prompts/resources/completion/elicitation, …). The 2026-era codec -* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. -* -* The 2025-only delta (the task message surface, restored types-only by #2248 -* for interop with task-capable 2025 peers) is parsed ONLY through this era's -* registry; the deprecated Task* schemas also live (marked `@deprecated`) in -* the neutral schema layer so the public types stay nameable without a -* cross-layer import — nameability is constant, runtime availability is -* version-keyed — but appear in no API signature. Q1 increment 2 — deletions -* are physical: the -* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do -* carry the deprecated Task* sub-schemas by composition — soft contamination, -* tracked for anchor-exactness adjudication). -* -* The only cross-layer dependency is `import type { JSONObject, JSONValue }` -* from the neutral types barrel — pure structural type aliases with no parse -* behavior. No runtime schema is shared with the neutral layer. -*/ -function build$1() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - /** - * Common params for any request. - */ - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** - * Common params for any task-augmented request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const RequestSchema$1 = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema$1.loose().optional() - }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * A response that indicates success but carries no data. - */ - const EmptyResultSchema$1 = ResultSchema$1.strict(); - const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - requestId: RequestIdSchema$1.optional(), - reason: schemas_string().optional() - }); - /** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. - */ - const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - /** - * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. - */ - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - /** - * Base schema to add `icons` property. - * - */ - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - /** - * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. - */ - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - /** - * Describes the name and version of an MCP implementation. - */ - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** - * Task capabilities for clients, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** - * Task capabilities for servers, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - /** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema$1, - clientInfo: ImplementationSchema$1 - }); - /** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ - const InitializeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema$1 - }); - /** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - /** - * After receiving an initialize request from the client, the server sends this response. - */ - const InitializeResultSchema$1 = ResultSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema$1, - serverInfo: ImplementationSchema$1, - instructions: schemas_string().optional() - }); - /** - * This notification is sent from the client to the server after initialization has finished. - */ - const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ - const PingRequestSchema$1 = RequestSchema$1.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema$1.optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - /** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); - const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); - const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); - /** - * The contents of a specific resource or sub-resource. - */ - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * Optional annotations providing clients additional context about a resource. - */ - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - /** - * A known resource that the server is capable of reading. - */ - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * A template description for resources available on the server. - */ - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of resources the server has. - */ - const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); - /** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ - const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); - /** - * Sent from the client to request a list of resource templates the server has. - */ - const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); - /** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ - const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); - const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); - /** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ - const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to the server, to read a specific resource URI. - */ - const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ - const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); - /** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ - const SubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema$1 - }); - const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - /** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - /** - * Describes an argument that a prompt can accept. - */ - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - /** - * A prompt or prompt template that the server offers. - */ - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ - const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); - /** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ - const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); - /** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ - const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }); - /** - * Used by the client to get a prompt provided by the server. - */ - const GetPromptRequestSchema$1 = RequestSchema$1.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema$1 - }); - /** - * Text provided to or from an LLM. - */ - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * An image provided to or from an LLM. - */ - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Audio content provided to or from an LLM. - */ - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * The contents of a resource, embedded into a prompt or tool call result. - */ - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. - */ - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - /** - * A content block that can be used in prompts and tool results. - */ - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - /** - * Describes a message returned as part of a prompt. - */ - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - /** - * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. - */ - const GetPromptResultSchema$1 = ResultSchema$1.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - /** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Additional properties describing a `Tool` to clients. - * - * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on `ToolAnnotations` - * received from untrusted servers. - */ - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - /** - * Execution-related properties for a tool. - */ - const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - /** - * Definition for a tool the client can call. - */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the client to request a list of tools the server has. - */ - const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); - /** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ - const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); - /** - * The server's response to a tool call. - */ - const CallToolResultSchema$1 = ResultSchema$1.extend({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_record(schemas_string(), unknown()).optional(), - isError: schemas_boolean().optional() - }); - /** - * Parameters for a `tools/call` request. - */ - const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Used by the client to invoke a tool provided by the server. - */ - const CallToolRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema$1 - }); - /** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * The severity of a log message. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * Parameters for a `logging/setLevel` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); - /** - * A request from the client to the server, to enable or adjust logging. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestSchema$1 = RequestSchema$1.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema$1 - }); - /** - * Parameters for a `notifications/message` notification. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - /** - * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - /** - * Hints to use for model selection. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - /** - * The server's preferences for model selection, requested of the client during sampling. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - /** - * Controls tool usage behavior in sampling requests. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - /** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via `ToolUseContent`. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_object({}).loose().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingContentSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1 - ]); - /** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** - * Describes a message issued to or received from an LLM API. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Parameters for a `sampling/createMessage` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request from the server. - * This is the backwards-compatible version that returns single content (no arrays). - * Used when the request does not include tools. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema$1, - content: SamplingContentSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request when tools were provided. - * This version supports array content for tool use flows. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) - }); - /** - * Primitive schema definition for boolean fields. - */ - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - /** - * Primitive schema definition for string fields. - */ - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - /** - * Primitive schema definition for number fields. - */ - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - /** - * Schema for single-selection enumeration without display titles for options. - */ - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - /** - * Schema for single-selection enumeration with display titles for each option. - */ - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - /** - * Use {@linkcode TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - */ - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - /** - * Schema for multiple-selection enumeration without display titles for options. - */ - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Schema for multiple-selection enumeration with display titles for each option. - */ - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Combined schema for multiple-selection enumeration - */ - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - /** - * Primitive schema definition for enum fields. - */ - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - /** - * Union of all primitive schema definitions. - */ - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - /** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - /** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ - const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() - }); - /** - * The parameters for a request to elicit additional information from the user via the client. - */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ - const ElicitRequestSchema$1 = RequestSchema$1.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); - /** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema$1 - }); - /** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ - const ElicitResultSchema$1 = ResultSchema$1.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) - }); - /** - * A reference to a resource or resource template definition. - */ - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - /** - * Identifies a prompt. - */ - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - /** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ - const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }); - /** - * A request from the client to the server, to ask for completion options. - */ - const CompleteRequestSchema$1 = RequestSchema$1.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode CompleteRequest | completion/complete} request - */ - const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) - }) }); - /** - * Represents a root directory or file that the server can operate on. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the server to request a list of root URIs from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsRequestSchema$1 = RequestSchema$1.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema$1.optional() - }); - /** - * The client's response to a `roots/list` request from the server. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); - /** - * A notification from the client to the server, informing it that the list of roots has changed. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Task creation parameters, used to ask that the server create a task to represent a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskCreationParamsSchema$1 = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() - }); - /** - * The status of a task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusSchema$1 = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - /** - * A pollable state object associated with a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskSchema$1 = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema$1, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) - }); - /** - * Result returned when a task is created, containing the task data wrapped in a `task` field. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); - /** - * Parameters for task status notification. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); - /** - * A notification sent when a task's status changes. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema$1 - }); - /** - * A request to get the state of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a {@linkcode GetTaskRequest | tasks/get} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); - /** - * A request to get the result of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a `tasks/result` request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. - * - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); - /** - * A request to list tasks. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); - /** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); - /** - * A request to cancel a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - RequestSchema: RequestSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - ResultSchema: ResultSchema$1, - RequestIdSchema: RequestIdSchema$1, - EmptyResultSchema: EmptyResultSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, - InitializeRequestSchema: InitializeRequestSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - InitializeResultSchema: InitializeResultSchema$1, - InitializedNotificationSchema: InitializedNotificationSchema$1, - PingRequestSchema: PingRequestSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, - PaginatedRequestSchema: PaginatedRequestSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - RoleSchema: RoleSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, - ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, - SubscribeRequestSchema: SubscribeRequestSchema$1, - UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, - UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolExecutionSchema: ToolExecutionSchema$1, - ToolSchema: ToolSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, - CallToolRequestSchema: CallToolRequestSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, - SetLevelRequestSchema: SetLevelRequestSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingContentSchema: SamplingContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, - ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - RootSchema: RootSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, - TaskCreationParamsSchema: TaskCreationParamsSchema$1, - TaskStatusSchema: TaskStatusSchema$1, - TaskSchema: TaskSchema$1, - CreateTaskResultSchema: CreateTaskResultSchema$1, - TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, - TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, - GetTaskRequestSchema: GetTaskRequestSchema$1, - GetTaskResultSchema: GetTaskResultSchema$1, - GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, - GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, - ListTasksRequestSchema: ListTasksRequestSchema$1, - ListTasksResultSchema: ListTasksResultSchema$1, - CancelTaskRequestSchema: CancelTaskRequestSchema$1, - CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), - ClientRequestSchema: schemas_union([ - PingRequestSchema$1, - InitializeRequestSchema$1, - CompleteRequestSchema$1, - SetLevelRequestSchema$1, - GetPromptRequestSchema$1, - ListPromptsRequestSchema$1, - ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema$1, - SubscribeRequestSchema$1, - UnsubscribeRequestSchema$1, - CallToolRequestSchema$1, - ListToolsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ClientNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - InitializedNotificationSchema$1, - RootsListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1 - ]), - ClientResultSchema: schemas_union([ - EmptyResultSchema$1, - CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema$1, - ElicitResultSchema$1, - ListRootsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - ServerRequestSchema: schemas_union([ - PingRequestSchema$1, - CreateMessageRequestSchema$1, - ElicitRequestSchema$1, - ListRootsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ServerNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - LoggingMessageNotificationSchema$1, - ResourceUpdatedNotificationSchema$1, - ResourceListChangedNotificationSchema$1, - ToolListChangedNotificationSchema$1, - PromptListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1, - ElicitationCompleteNotificationSchema$1 - ]), - ServerResultSchema: schemas_union([ - EmptyResultSchema$1, - InitializeResultSchema$1, - CompleteResultSchema$1, - GetPromptResultSchema$1, - ListPromptsResultSchema$1, - ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema$1, - CallToolResultSchema$1, - ListToolsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - CallToolResultWireSchema: unknown().superRefine((value, ctx) => { - if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; - for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { - ctx.addIssue({ - code: "custom", - message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` - }); - return; - } - }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) - }; -} -let memo$1; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2025() { - return memo$1 ??= build$1(); -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts -/** -* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). -* -* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON -* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, -* so when an era-blind handler advertises a non-object root, the 2025 codec's -* `encodeResult('tools/list', …)` projects it down to -* `{type:'object', properties:{result:}, required:['result']}`, and -* `projectCallToolResult` wraps the matching `structuredContent` as -* `{result:}`. The 2026 codec's projections are the identity. -* -* These helpers are wire-layer property — they exist so the projection can -* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} -* and never be re-derived in shared/ or server-side code. -*/ -/** -* Whether a JSON Schema's root is non-object: either an explicit non-object -* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless -* roots that the schema-conversion layer can prove are objects are stamped -* `type:'object'` upstream, so they reach this predicate as object roots. -*/ -function isNonObjectJsonSchemaRoot(json) { - return json["type"] !== "object"; -} -/** -* Keyword-position keys whose values are instance data (not subschemas). A -* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to -* rewrite. Only consulted when the current object is in keyword position — -* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name -* position whose value IS a subschema and is recursed into. -*/ -const REF_REWRITE_DATA_POSITION_KEYS = new Set([ - "const", - "enum", - "default", - "examples" -]); -/** -* Keyword-position keys whose value is a name→subschema map. Entries inside -* such a map are in NAME position: their keys are author-chosen property -* names (which may collide with JSON Schema keywords), their values are -* subschemas to recurse into. -*/ -const REF_REWRITE_NAME_MAP_KEYS = new Set([ - "properties", - "patternProperties", - "$defs", - "definitions", - "dependentSchemas", - "dependencies" -]); -/** -* Whether a subtree's `$id` establishes a new resolution base. A fragment-only -* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not -* change the RFC 3986 base URI — same-document pointers inside still resolve -* against the document root and must be rewritten. -*/ -function establishesNewBase(id) { - return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); -} -/** -* Wrap a non-object output schema in the 2025-era envelope: -* `{type:'object', properties:{result:}, required:['result']}`. -* -* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema -* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) -* are rewritten to account for the new `#/properties/result` root: bare `#` → -* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs -* (anything not starting with `#`) are left untouched. -* -* The rewrite is position-aware: data-valued keywords -* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended -* into; the same names appearing as property names under -* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ -* `dependencies` ARE descended into (they're subschemas). The rewrite is also -* `$id`-scoped: if the natural root carries a base-establishing `$id` no -* pointer is rewritten (same-document refs inside resolve against the embedded -* `$id` base, not the wrapper root), and any subtree that establishes its own -* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, -* draft-07's anchor spelling) does not establish a base and IS descended into. -*/ -function wrapOutputSchemaForLegacy(natural) { - const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; - if (establishesNewBase(natural["$id"])) return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: natural }, - required: ["result"] - }; - const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; - const rewriteRefs = (node, parentIsNameMap) => { - if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); - if (node === null || typeof node !== "object") return node; - if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; - const out = {}; - let convertedRecursion = false; - for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); - else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; - else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; - else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; - else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); - else out[k] = rewriteRefs(v, false); - if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; - else out["$ref"] = "#/properties/result"; - return out; - }; - return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: rewriteRefs(natural, false) }, - required: ["result"] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/registry.ts -const requestMethodKeys$1 = { - ping: null, - initialize: null, - "completion/complete": null, - "logging/setLevel": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "resources/subscribe": null, - "resources/unsubscribe": null, - "tools/call": null, - "tools/list": null, - "tasks/get": null, - "tasks/result": null, - "tasks/list": null, - "tasks/cancel": null, - "sampling/createMessage": null, - "elicitation/create": null, - "roots/list": null -}; -const notificationMethodKeys$1 = { - "notifications/cancelled": null, - "notifications/progress": null, - "notifications/initialized": null, - "notifications/roots/list_changed": null, - "notifications/tasks/status": null, - "notifications/message": null, - "notifications/resources/updated": null, - "notifications/resources/list_changed": null, - "notifications/tools/list_changed": null, - "notifications/prompts/list_changed": null, - "notifications/elicitation/complete": null -}; -const resultMethodKeys = { - ping: null, - initialize: null, - "completion/complete": null, - "logging/setLevel": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "resources/subscribe": null, - "resources/unsubscribe": null, - "tools/call": null, - "tools/list": null, - "sampling/createMessage": null, - "elicitation/create": null, - "roots/list": null -}; -let maps$1; -function registryMaps() { - if (maps$1) return maps$1; - const s = buildSchemas2025(); - maps$1 = { - requestSchemas: { - ping: s.PingRequestSchema, - initialize: s.InitializeRequestSchema, - "completion/complete": s.CompleteRequestSchema, - "logging/setLevel": s.SetLevelRequestSchema, - "prompts/get": s.GetPromptRequestSchema, - "prompts/list": s.ListPromptsRequestSchema, - "resources/list": s.ListResourcesRequestSchema, - "resources/templates/list": s.ListResourceTemplatesRequestSchema, - "resources/read": s.ReadResourceRequestSchema, - "resources/subscribe": s.SubscribeRequestSchema, - "resources/unsubscribe": s.UnsubscribeRequestSchema, - "tools/call": s.CallToolRequestSchema, - "tools/list": s.ListToolsRequestSchema, - "tasks/get": s.GetTaskRequestSchema, - "tasks/result": s.GetTaskPayloadRequestSchema, - "tasks/list": s.ListTasksRequestSchema, - "tasks/cancel": s.CancelTaskRequestSchema, - "sampling/createMessage": s.CreateMessageRequestSchema, - "elicitation/create": s.ElicitRequestSchema, - "roots/list": s.ListRootsRequestSchema - }, - notificationSchemas: { - "notifications/cancelled": s.CancelledNotificationSchema, - "notifications/progress": s.ProgressNotificationSchema, - "notifications/initialized": s.InitializedNotificationSchema, - "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, - "notifications/tasks/status": s.TaskStatusNotificationSchema, - "notifications/message": s.LoggingMessageNotificationSchema, - "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, - "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, - "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, - "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, - "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema - }, - resultSchemas: { - ping: s.EmptyResultSchema, - initialize: s.InitializeResultSchema, - "completion/complete": s.CompleteResultSchema, - "logging/setLevel": s.EmptyResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "resources/subscribe": s.EmptyResultSchema, - "resources/unsubscribe": s.EmptyResultSchema, - "tools/call": s.CallToolResultWireSchema, - "tools/list": s.ListToolsResultSchema, - "sampling/createMessage": s.CreateMessageResultWithToolsSchema, - "elicitation/create": s.ElicitResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps$1; -} -/** -* Forces the lazy registry maps (and, through them, the era's schema memo). -* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmRegistryMaps2025() { - registryMaps(); -} -/** The 2025-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2025(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); -} -/** The 2025-era notification-method set. */ -function hasNotificationMethod2025(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); -} -/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ -function hasResultMethod(method) { - return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); -} -function getResultSchema(method) { - return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; -} -function getRequestSchema(method) { - return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; -} -function getNotificationSchema(method) { - return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2025RequestMethods = Object.keys(requestMethodKeys$1); -const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/codec.ts -function isPlainObject$6(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState$1(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA$1 = { - ok: false, - reason: "not-in-era" -}; -/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ -function toolNeedsLegacyWrap(t) { - return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); -} -/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ -function toNeutralResult(value) { - return value; -} -const rev2025Codec = { - era: "2025-11-25", - hasRequestMethod: hasRequestMethod2025, - hasNotificationMethod: hasNotificationMethod2025, - validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), - validateResult: (method, raw) => triState$1(getResultSchema(method), raw), - validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), - hasInputRequestMethod: () => false, - validateInputRequest: () => NOT_IN_ERA$1, - validateInputResponse: () => NOT_IN_ERA$1, - samplingResultVariant: ((hasTools, raw) => { - const s = buildSchemas2025(); - return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); - }), - outboundEnvelope: (_material) => void 0, - validateEnvelopeMeta: (_meta) => [], - projectCallToolResult(result, advertisedOutputSchema) { - const withText = appendTextFallbackForNonObject(result); - const sc = withText.structuredContent; - if (sc === void 0) return withText; - const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); - const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); - if (!valueIsNonObject && !schemaWrapped) return withText; - return { - ...withText, - structuredContent: { result: sc } - }; - }, - decodeResult(_method, raw) { - if (isPlainObject$6(raw) && "resultType" in raw) { - const stripped = { ...raw }; - delete stripped["resultType"]; - return { - kind: "complete", - result: toNeutralResult(stripped) - }; - } - return { - kind: "complete", - result: toNeutralResult(raw) - }; - }, - encodeResult(method, result) { - if (method !== "tools/list") return result; - const tools = result.tools; - if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; - return { - ...result, - tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { - ...t, - outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) - } : t) - }; - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope: (_material) => void 0 -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts -/** -* 2026-era wire schemas (protocol revision 2026-07-28). -* -* Fully self-contained — no runtime imports from types/schemas.ts. The -* neutral types/schemas.ts layer is the public-API superset and is free to -* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN -* against the 2026-07-28 anchor. Every era-shared building block (content -* blocks, resources, prompts, capabilities, notifications, …) that the wire -* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at -* the point this revision was sealed, dependencies first. The only cross-layer -* dependency is `import type { JSONObject, JSONValue }` from the neutral types -* barrel — pure structural type aliases with no parse behavior. -* -* This module is the only place the per-request `_meta` envelope is modeled. -* The envelope is wire-only vocabulary: the protocol layer lifts it off -* inbound requests before any handler runs and surfaces it at -* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at -* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc -* deferral ("enforced per request at dispatch time, not here") is now -* discharged by that codec step. -* -* No 2025-era traffic ever touches this module, so requiredness here is -* bare and spec-exact (the shared-schema `.catch` hazards do not apply). -* -* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed -* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the -* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from -* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result -* body to the new `ResultMetaObject` key -* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). -* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is -* modeled anywhere (per ruling: the final revision is the only 2026-07-28). -*/ -function build() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * The severity of a log message. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; - const ClientCapabilities2026Schema = schemas_object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions - }); - const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; - const ServerCapabilities2026Schema = schemas_object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions - }); - /** - * The per-request `_meta` envelope carried by every request under protocol revision - * 2026-07-28: the protocol version governing the request, the client implementation - * info, and the client's capabilities — declared per request rather than once at - * initialization — plus the optional log-level opt-in. - * - * This schema models the complete envelope on its own (loose: foreign keys - * pass through - the lift extracts exactly the reserved keys, so enforcement - * never sees extension material). Requiredness is enforced per request at - * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. - */ - const RequestMetaEnvelopeSchema = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() - }); - /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: looseObject({ - $schema: schemas_string().optional(), - type: literal("object") - }), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string(), - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era sampling content union (composes the forked tool-result shape). */ - const SamplingMessageContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** 2026-era SamplingMessage (anchor-exact: single block or array). */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** Open union per the anchor: 'complete' | 'input_required' | string. */ - const ResultTypeSchema = schemas_string(); - /** - * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): - * loose, with the serverInfo key typed when present; the outbound stamp - * is the encode contract's `stampServerInfoMeta` step. - */ - const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); - const wireMeta = ResultMetaSchema.optional(); - function wireResult(shape) { - return looseObject({ - _meta: wireMeta, - resultType: ResultTypeSchema.default("complete"), - ...shape - }); - } - const ResultSchema$1 = wireResult({}); - const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); - const CallToolResultSchema$1 = wireResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }); - const ListToolsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const GetPromptResultSchema$1 = wireResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - const ListResourcesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListResourceTemplatesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ReadResourceResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }); - const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }); - /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ - const CacheableResultSchema = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]) - }); - const DiscoverResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }); - /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ - const CreateMessageRequestParamsSchema$1 = schemas_object({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** 2026-era embedded sampling request (de-JSON-RPC'd). */ - const CreateMessageRequestSchema$1 = schemas_object({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input - * requests do NOT carry the per-request `_meta` envelope on this revision — - * the anchor declares a bare optional `_meta` on `params`. - */ - const ListRootsRequestSchema$1 = schemas_object({ - method: literal("roots/list"), - params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() - }); - /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ - const CreateMessageResultSchema$1 = schemas_object({ - ...SamplingMessageSchema$1.shape, - model: schemas_string(), - stopReason: schemas_string().optional() - }); - /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ - const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); - /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ - const ElicitResultSchema$1 = schemas_object({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional() - }); - /** - * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed - * `elicitationId` (and the `notifications/elicitation/complete` channel it - * keyed) — the shared schema keeps the field because it is required on the - * frozen 2025-11-25 revision. - */ - const ElicitRequestURLParamsSchema$1 = schemas_object({ - mode: literal("url"), - message: schemas_string(), - url: schemas_string().url() - }); - /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ - const ElicitRequestSchema$1 = schemas_object({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** A single embedded input request (one of the three demoted server→client requests). */ - const InputRequestSchema = schemas_union([ - CreateMessageRequestSchema$1, - ListRootsRequestSchema$1, - ElicitRequestSchema$1 - ]); - /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ - const InputResponseSchema = schemas_union([ - CreateMessageResultSchema$1, - ListRootsResultSchema$1, - ElicitResultSchema$1 - ]); - /** Map of embedded input requests, keyed by server-assigned identifiers. */ - const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); - /** Map of embedded input responses, keyed by the corresponding request identifiers. */ - const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); - /** - * The wire InputRequiredResult: `resultType: 'input_required'` plus at least - * one of `inputRequests` / `requestState` (the at-least-one rule is enforced - * at the server seam, not by this parse shape). - */ - const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: schemas_string().optional() - }); - /** The retry-channel members carried by client-initiated requests on this revision. */ - const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: schemas_string().optional() - }; - /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ - const InputResponseRequestParamsSchema = schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape - }); - /** Post-lift request `_meta` (progressToken + extension keys; loose). */ - const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); - function wireRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...paramsShape - }) - }); - } - function dispatchRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: DispatchRequestMetaSchema.optional(), - ...paramsShape - }).optional() - }); - } - const callToolParamsShape = { - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional(), - ...retryParamsShape - }; - const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; - const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); - const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); - const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); - const GetPromptRequestSchema$1 = wireRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional(), - ...retryParamsShape - }); - const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); - const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); - const ReadResourceRequestSchema$1 = wireRequest("resources/read", { - uri: schemas_string(), - ...retryParamsShape - }); - const completeParamsShape = { - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }; - const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); - const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); - /** Anchor SubscriptionFilter (2026-only). */ - const SubscriptionFilterSchema$1 = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() - }); - const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; - const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); - /** - * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on - * the graceful-close result. Extends `ResultMetaObject` since spec PR - * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). - */ - const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); - /** - * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` - * response signalling that the subscription has ended gracefully (server - * shutdown). An abrupt transport close carries no response — the client treats - * stream-close-without-result as a disconnect. - */ - const SubscriptionsListenResultSchema$1 = looseObject({ - _meta: SubscriptionsListenResultMetaSchema$1, - resultType: ResultTypeSchema.default("complete") - }); - /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ - const dispatchRequestSchemas = { - "tools/call": dispatchRequest("tools/call", callToolParamsShape), - "tools/list": dispatchRequest("tools/list", paginatedParamsShape), - "prompts/get": dispatchRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }), - "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), - "resources/list": dispatchRequest("resources/list", paginatedParamsShape), - "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), - "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), - "completion/complete": dispatchRequest("completion/complete", completeParamsShape), - "server/discover": dispatchRequest("server/discover", {}), - "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) - }; - /** Dispatch (post-lift) result schemas, keyed by method — what the funnel - * validates AFTER `decodeResult` consumed `resultType`. */ - function liftedResult(shape) { - return looseObject({ - _meta: wireMeta, - ...shape - }); - } - const dispatchResultSchemas = { - "tools/call": liftedResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }), - "tools/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }), - "prompts/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/templates/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/read": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }), - "completion/complete": liftedResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }), - "server/discover": liftedResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }), - "subscriptions/listen": liftedResult({}) - }; - /** - * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the - * subscriptions/listen demux key typed when present. Only the anchor-exact - * SHAPE is modeled here — listen delivery itself (filter gating, demux, - * teardown) is #14 scope and not implemented by this module. - */ - const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); - /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ - const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ - method: literal("notifications/subscriptions/acknowledged"), - params: schemas_object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema$1 - }) - }); - /** - * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` - * is REQUIRED on this revision — the shared schema keeps it optional because - * the frozen 2025-11-25 shape declares it optional (task cancellation goes - * through `tasks/cancel` there). Requiredness is bare because no 2025-era - * traffic touches this module. - */ - const CancelledNotificationParamsSchema$1 = schemas_object({ - _meta: NotificationMetaSchema.optional(), - requestId: RequestIdSchema$1, - reason: schemas_string().optional() - }); - /** 2026-era `notifications/cancelled` (see the params fork above). */ - const CancelledNotificationSchema$1 = schemas_object({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - const notificationSchemas2026 = { - "notifications/cancelled": CancelledNotificationSchema$1, - "notifications/progress": ProgressNotificationSchema$1, - "notifications/message": LoggingMessageNotificationSchema$1, - "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, - "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, - "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, - "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, - "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 - }; - const wireResultResponse = (result) => schemas_object({ - jsonrpc: literal("2.0"), - id: schemas_union([schemas_string(), schemas_number().int()]), - result - }).strict(); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - RequestIdSchema: RequestIdSchema$1, - RoleSchema: RoleSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - RootSchema: RootSchema$1, - ClientCapabilities2026Schema, - ServerCapabilities2026Schema, - RequestMetaEnvelopeSchema, - ToolSchema: ToolSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - ResultTypeSchema, - ResultMetaSchema, - ResultSchema: ResultSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - CacheableResultSchema, - DiscoverResultSchema: DiscoverResultSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - InputRequestSchema, - InputResponseSchema, - InputRequestsSchema, - InputResponsesSchema, - InputRequiredResultSchema, - InputResponseRequestParamsSchema, - CallToolRequestSchema: CallToolRequestSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - DiscoverRequestSchema: DiscoverRequestSchema$1, - SubscriptionFilterSchema: SubscriptionFilterSchema$1, - SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, - SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, - SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, - dispatchRequestSchemas, - dispatchResultSchemas, - NotificationMetaSchema, - SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - notificationSchemas2026, - JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), - CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), - ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), - ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), - GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), - ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), - ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), - ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), - CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), - DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) - }; -} -let src_CX2iR2pK_memo; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2026() { - return src_CX2iR2pK_memo ??= build(); -} - -//#endregion -//#region ../core-internal/src/shared/resultCacheHints.ts -/** -* The operations whose results are cacheable on the 2026-07-28 revision (the -* `CacheableResult` extenders). This list is closed: no other operation's -* result ever receives cache fields from the SDK. -*/ -const CACHEABLE_RESULT_METHODS = [ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "resources/read", - "server/discover" -]; -/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ -function isCacheableResultMethod(method) { - return CACHEABLE_RESULT_METHODS.includes(method); -} -/** -* The symbol-keyed carrier for a configured cache hint on a result object. -* Symbol properties are invisible to JSON serialization, so the carrier can be -* attached era-blind: only the 2026-era encode seam consumes it. -*/ -const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); -/** -* Attaches a configured cache hint to a result as the encode-time fallback. -* Returns the result unchanged when there is nothing to attach. When a more -* specific hint is already attached, the two hints are combined per field -* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the -* per-registration hint attached by the feature layer keeps every field it -* sets, and the server-level per-operation hint only fills the fields the -* more specific hint leaves unset. -*/ -function attachCacheHintFallback(result, hint) { - if (hint === void 0) return result; - const attached = result[RESULT_CACHE_HINT_FALLBACK]; - if (attached === void 0) return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: hint - }; - const merged = {}; - const ttlMs = attached.ttlMs ?? hint.ttlMs; - if (ttlMs !== void 0) merged.ttlMs = ttlMs; - const cacheScope = attached.cacheScope ?? hint.cacheScope; - if (cacheScope !== void 0) merged.cacheScope = cacheScope; - return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: merged - }; -} -/** Reads the configured cache-hint fallback attached to a result, if any. */ -function cacheHintFallbackOf(result) { - return result[RESULT_CACHE_HINT_FALLBACK]; -} -/** -* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe -* integers are required because the wire schemas validate `ttlMs` as an -* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value -* outside that range is treated as invalid here so it falls through to the -* next author instead of being emitted and rejected downstream. -*/ -function isValidCacheTtlMs(value) { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; -} -/** Whether a value is a valid `cacheScope`. */ -function isValidCacheScope(value) { - return value === "public" || value === "private"; -} -/** -* Validates a configured cache hint at configuration time. Throws a -* `RangeError` naming the offending field, so misconfiguration fails at -* startup/registration rather than silently degrading at encode time. -*/ -function assertValidCacheHint(hint, context) { - if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); - if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); -} - -//#endregion -//#region ../core-internal/src/types/enums.ts -/** -* Error codes for protocol errors that cross the wire as JSON-RPC error responses. -* These follow the JSON-RPC specification and MCP-specific extensions. -*/ -let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { - ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; - ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; - /** - * Resource not found. - * - * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` - * misses answer `-32602` (Invalid Params) on every protocol revision per - * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to - * `-32602` at the era encode seam. The member stays importable so clients - * can recognise `-32002` from peers built on earlier SDK releases (the - * spec's "clients SHOULD also accept `-32002`" backwards-compatibility - * clause). Throw `ResourceNotFoundError` instead. - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; - /** - * Processing the request requires a capability the client did not declare - * in the request's `clientCapabilities` (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; - /** - * The request's protocol version is unknown to the server or unsupported - * by it (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; - return ProtocolErrorCode$1; -}({}); - -//#endregion -//#region ../core-internal/src/types/errors.ts -/** -* Protocol errors are JSON-RPC errors that cross the wire as error responses. -* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. -* -* `instanceof` on this class (and its subclasses) is brand-matched, so it works -* across separately bundled copies of the SDK — e.g. an error constructed by -* `@modelcontextprotocol/client` matches the class re-exported by -* `@modelcontextprotocol/server` in the same process. -*/ -var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "ProtocolError"; - stampErrorBrands(this, new.target); - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { - const errorData = data; - if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: errorData.supported, - requested: errorData.requested - }, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { - const errorData = data; - if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { - const errorData = data; - if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); - } - return new ProtocolError(code, message, data); - } -}; -/** -* Error type for a `resources/read` miss: the requested resource does not -* exist. The wire code is `-32602` (Invalid Params) on every protocol -* revision — the spec MUST for revision 2026-07-28, and the value the v1.x -* SDK has always emitted on earlier revisions. The error data echoes the -* requested URI. -* -* Recognise this error by checking `error.data` is exactly `{ uri: string }` -* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; -* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also -* accept `-32002` as resource not found — earlier SDK builds emitted that -* code, and {@linkcode ProtocolError.fromError} reconstructs this class for -* either code **when `error.data` carries `uri`** (a bare `-32002` without -* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks -* are brand-matched and work across separately bundled copies of the SDK. -*/ -var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); - } - constructor(uri, message = `Resource not found: ${uri}`) { - super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); - } - /** The URI that was requested and not found. */ - get uri() { - return this.data.uri; - } -}; -/** -* Specialized error type when a tool requires a URL mode elicitation. -* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. -*/ -var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); - } - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -}; -/** -* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol -* revision 2026-07-28): the request's protocol version is unknown to the server or -* unsupported by it. -* -* The error data lists the protocol versions the receiver supports (`supported`), -* so the sender can choose a mutually supported version and retry, and echoes the -* version that was requested (`requested`). -*/ -var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); - } - constructor(data, message = `Unsupported protocol version: ${data.requested}`) { - super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); - } - /** - * Protocol versions the receiver supports. - */ - get supported() { - return this.data.supported; - } - /** - * The protocol version that was requested. - */ - get requested() { - return this.data.requested; - } -}; -/** -* Error type for the `-32021` MissingRequiredClientCapability protocol error -* (protocol revision 2026-07-28): processing the request requires a capability -* the client did not declare in the request's `clientCapabilities`. -* -* The error data lists the missing capabilities (`requiredCapabilities`) in -* the `ClientCapabilities` shape, so the client can see exactly what it would -* have to declare for the request to be served. On HTTP, the response status -* is `400 Bad Request`. -* -* Recognize this error by its code and `data.requiredCapabilities`, or by -* `instanceof` — checks are brand-matched and work across separately bundled -* copies of the SDK. -*/ -var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); - } - constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { - super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); - } - /** - * The capabilities the server requires from the client to process the - * request (only the missing capabilities are listed). - */ - get requiredCapabilities() { - return this.data.requiredCapabilities; - } -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts -/** The default cache policy when neither the handler nor configuration provides one. */ -const DEFAULT_CACHE_TTL_MS = 0; -const DEFAULT_CACHE_SCOPE = "private"; -/** -* Request methods whose spec result vocabulary goes beyond `'complete'` on the -* 2026-07-28 revision: their results may be `input_required` (multi -* round-trip requests), so a handler-provided `resultType` passes through the -* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits -* a JSON-RPC result — termination is stream close (HTTP) or -* `notifications/cancelled` (stdio) per the spec. -*/ -const EXTENDED_RESULT_TYPE_METHODS = [ - "tools/call", - "prompts/get", - "resources/read" -]; -/** -* Step 1 of the encode contract: ensure the outbound result carries the -* required `resultType` discriminator. -* -* - No handler-provided value → stamp `'complete'`. -* - Handler-provided `'complete'` → kept as-is. -* - Handler-provided non-`'complete'` value on a method whose vocabulary -* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. -* The value is forwarded verbatim — the wire vocabulary is an open union and -* the SDK does not validate the string, so emitting a `resultType` the -* negotiated revision does not define is the handler author's -* responsibility. -* - Handler-provided non-`'complete'` value on any other method → internal -* error (loud): the value would be mis-typed on the wire, and silently -* rewriting it would hide a server bug. -*/ -function stampResultType(method, result) { - const provided = result["resultType"]; - if (provided === void 0) return { - ...result, - resultType: "complete" - }; - if (provided === "complete") return result; - if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); -} -/** -* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields -* on cacheable results. -* -* Applies only when the (post-stamp) `resultType` is `'complete'` and the -* method is one of the cacheable operations; everything else is returned -* untouched apart from removing the configured-hint carrier. Field resolution -* is per field, most specific author first: a valid handler-returned value, -* then the configured cache hint attached by the server layer, then the -* defaults. Handler-returned values are validated at encode time (`ttlMs` -* must be a non-negative integer, `cacheScope` must be `'public'` or -* `'private'`); invalid values are ignored rather than emitted. -*/ -function fillCacheFields(method, result) { - const fallback = cacheHintFallbackOf(result); - if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); - const provided = result; - const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); - const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); - const filled = { - ...provided, - ttlMs, - cacheScope - }; - delete filled[RESULT_CACHE_HINT_FALLBACK]; - return filled; -} -function isPlainObject$5(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Step 3 of the encode contract: stamp the server's identity into the -* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: -* servers SHOULD include it on every response). -* -* - No `serverInfo` supplied (a client instance, or a hand-constructed -* protocol object) → identity function. -* - The result's `_meta` already carries the key → kept as-is (the handler -* is the more specific author; mirrors the cache-fill resolution order). -* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: -* the stamp never rewrites handler material, and the malformed value fails -* loudly at the peer instead of being silently replaced here. -* - Otherwise → the key is added, preserving any other `_meta` entries. -* -* Runs for every result regardless of `resultType`: the anchor types -* `Result._meta` as `ResultMetaObject` on all results, `input_required` -* included. -*/ -function stampServerInfoMeta(result, serverInfo) { - if (serverInfo === void 0) return result; - const meta = result["_meta"]; - if (meta === void 0) return { - ...result, - _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } - }; - if (!isPlainObject$5(meta)) return result; - if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; - return { - ...result, - _meta: { - ...meta, - [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo - } - }; -} -function resolveTtlMs(fallback) { - return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; -} -function resolveCacheScope(fallback) { - return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; -} -function stripCacheHintFallback(result) { - const copy = { ...result }; - delete copy[RESULT_CACHE_HINT_FALLBACK]; - return copy; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts -/** -* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 -* multi round-trip requests), dispatch view. -* -* The three former server→client wire requests (`elicitation/create`, -* `sampling/createMessage`, `roots/list`) are NOT wire request methods on -* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an -* `input_required` result. The multi-round-trip driver dispatches those -* embedded payloads to the client's registered handlers through the normal -* handler machinery, and these are the schemas that dispatch parses them -* with: lenient where the anchor's wire-true artifacts are strict (an -* embedded request never carries the per-request `_meta` envelope), exact -* where the vocabulary forks (the sampling shapes compose the forked -* SamplingMessage/Tool payloads). -* -* Registry membership is intentionally NOT granted here — these methods stay -* absent from the 2026-era request registry (a peer sending one as a wire -* request still gets −32601 by absence). Only the codec's -* `inputRequestSchema`/`inputResponseSchema` accessors expose them. -*/ -/** The embedded input-request methods of the 2026-07-28 revision. */ -const INPUT_REQUEST_METHODS_2026 = [ - "elicitation/create", - "sampling/createMessage", - "roots/list" -]; -let maps; -function inputSchemaMaps() { - if (maps) return maps; - const s = buildSchemas2026(); - maps = { - request: { - "elicitation/create": schemas_object({ - method: literal("elicitation/create"), - params: s.ElicitRequestParamsSchema - }), - "sampling/createMessage": schemas_object({ - method: literal("sampling/createMessage"), - params: s.CreateMessageRequestParamsSchema - }), - "roots/list": schemas_object({ - method: literal("roots/list"), - params: looseObject({}).optional() - }) - }, - response: { - "elicitation/create": s.ElicitResultSchema, - "sampling/createMessage": s.CreateMessageResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps; -} -/** -* Forces the lazy embedded-request maps (and, through them, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmInputSchemaMaps2026() { - inputSchemaMaps(); -} -function isInputRequestMethod2026(method) { - return INPUT_REQUEST_METHODS_2026.includes(method); -} -function getInputRequestSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; -} -function getInputResponseSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/registry.ts -const requestMethodKeys = { - "tools/call": null, - "tools/list": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "completion/complete": null, - "server/discover": null, - "subscriptions/listen": null -}; -const notificationMethodKeys = { - "notifications/cancelled": null, - "notifications/progress": null, - "notifications/message": null, - "notifications/resources/updated": null, - "notifications/resources/list_changed": null, - "notifications/tools/list_changed": null, - "notifications/prompts/list_changed": null, - "notifications/subscriptions/acknowledged": null -}; -/** The 2026-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -/** The 2026-era notification-method set. */ -function hasNotificationMethod2026(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); -} -/** Result-map membership (same key set as the request map on this era). */ -function hasResultMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -function getRequestSchema2026(method) { - return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; -} -function getResultSchema2026(method) { - return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; -} -function getNotificationSchema2026(method) { - return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2026RequestMethods = Object.keys(requestMethodKeys); -const rev2026NotificationMethods = Object.keys(notificationMethodKeys); - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/codec.ts -function isPlainObject$4(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA = { - ok: false, - reason: "not-in-era" -}; -/** -* The reserved `_meta` keys an envelope must carry on this era (in reporting -* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a -* request without it is accepted (a present-but-malformed value still fails -* the envelope schema parse below). -*/ -const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; -/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ -function enforceDeletedFields(method, result) { - let next = result; - let copied = false; - const copy = () => { - if (!copied) { - next = { ...next }; - copied = true; - } - return next; - }; - const tools = result.tools; - if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { - if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; - const rest = { ...tool }; - delete rest["execution"]; - return rest; - }); - const capabilities = result.capabilities; - if (isPlainObject$4(capabilities) && "tasks" in capabilities) { - const rest = { ...capabilities }; - delete rest["tasks"]; - copy().capabilities = rest; - } - return next; -} -const rev2026Codec = { - era: "2026-07-28", - hasRequestMethod: hasRequestMethod2026, - hasNotificationMethod: hasNotificationMethod2026, - hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, - validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), - validateResult: (method, raw) => triState(getResultSchema2026(method), raw), - validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), - validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), - validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), - samplingResultVariant: () => NOT_IN_ERA, - outboundEnvelope(material) { - return { - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, - ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } - }; - }, - validateEnvelopeMeta(meta) { - const issues = []; - for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ - key, - problem: "missing" - }); - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); - if (!parsed.success) for (const issue of parsed.error.issues) { - const path = issue.path.map(String); - const key = path.length > 0 ? path.join(".") : "_meta"; - if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; - issues.push({ - key, - problem: issue.message - }); - } - return issues; - }, - projectCallToolResult: (result) => appendTextFallbackForNonObject(result), - inputRequestSchema: getInputRequestSchema2026, - decodeResult(method, raw) { - if (!isPlainObject$4(raw)) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) - }; - const rawResultType = raw["resultType"]; - if (rawResultType === void 0) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { - method, - violation: "missing-resultType" - }) - }; - if (typeof rawResultType !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { - method, - resultType: rawResultType - }) - }; - if (rawResultType === "input_required") { - const rawInputRequests = raw["inputRequests"]; - const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; - const requestState = raw["requestState"]; - if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { - method, - violation: "input-required-missing-both" - }) - }; - return { - kind: "input_required", - inputRequests, - ...typeof requestState === "string" && { requestState } - }; - } - if (rawResultType !== "complete") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { - resultType: rawResultType, - method - }) - }; - const wireResultSchemas = getWireResultSchemas(); - const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; - if (wireSchema !== void 0) { - const parsed = wireSchema.safeParse(raw); - if (!parsed.success) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) - }; - } - const lifted = { ...raw }; - delete lifted["resultType"]; - return { - kind: "complete", - result: lifted - }; - }, - encodeResult(method, result, serverInfo) { - return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope(material) { - if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); - if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; - } -}; -/** Wire-true result wrappers consulted by decode step 2, keyed by method — -* built once through the era's schema memo on the first decode. */ -let wireResultSchemasMemo; -function getWireResultSchemas() { - if (wireResultSchemasMemo) return wireResultSchemasMemo; - const s = buildSchemas2026(); - wireResultSchemasMemo = { - "tools/call": s.CallToolResultSchema, - "tools/list": s.ListToolsResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "completion/complete": s.CompleteResultSchema, - "server/discover": s.DiscoverResultSchema - }; - return wireResultSchemasMemo; -} -/** -* Forces the lazy wire-result wrapper map (and, through it, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. -*/ -function warmWireResultSchemas2026() { - getWireResultSchemas(); -} - -//#endregion -//#region ../core-internal/src/wire/codec.ts -/** -* The modern wire revision literal. Internal only — deliberately NOT a public -* constant (G-D2-4: no public modern-version constant ships before era-aware -* list semantics exist). -*/ -const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; -/** -* Era resolution, many-to-one (Q1-SD1): every modern-era revision -* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five -* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era -* codec (the DV-13 default posture — hand-constructed instances and -* unclassified traffic are legacy-era). This is the same era predicate the -* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern -* revision other than the literal '2026-07-28' must still resolve modern. -*/ -function src_CX2iR2pK_codecForVersion(version) { - return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; -} -/** -* The wire era an edge classification names (Q2 — produced at the -* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no -* longer resolves a codec FROM the classification: era is instance state, and -* a classified inbound message is VALIDATED against the instance era — a -* mismatch is an entry/routing error, never a per-message era switch. The -* exact `revision` wins over the coarse era flag when both are present. -*/ -function classifiedWireEra(classification) { - if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; - return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; -} -/** -* The derived spec-method universe: the union of every codec registry. A -* method in this set is era-gated at dispatch and send time; a method outside -* it is a consumer-owned extension method (era-blind, schema-explicit). -* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS -* table class is exactly what registry membership replaces). -*/ -function isSpecRequestMethod(method) { - return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); -} -function isSpecNotificationMethod(method) { - return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); -} -const ALL_CODECS = [rev2025Codec, rev2026Codec]; - -//#endregion -//#region ../core-internal/src/shared/envelope.ts -/** -* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). -* -* Pure, value-returning helpers used by the inbound HTTP classifier -* (`classifyInboundRequest`): claim detection and envelope validation with -* self-identifying issues. The envelope schema itself stays the wire layer's -* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps -* its outcomes into the shapes the validation ladder emits. -* -* Claim detection is deliberately narrow: a message claims the 2026-07-28 -* envelope mechanism if and only if the reserved protocol-version `_meta` key -* is present in `params._meta`. Other reserved keys (client info, client -* capabilities, log level), a bare `progressToken`, or unrelated keys under -* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their -* own — but once the claim key is present, a malformed envelope is a -* validation error, never a silent fall back to legacy handling. -* -* The wire-exact envelope schema, the required-key set, and the per-key issue -* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). -* This module never reaches into a per-revision wire module directly. -*/ -function isPlainObject$3(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** The `_meta` object of a message's params, when present. */ -function src_CX2iR2pK_requestMetaOf(params) { - if (!isPlainObject$3(params)) return void 0; - const meta = params["_meta"]; - return isPlainObject$3(meta) ? meta : void 0; -} -/** -* Whether a message's params carry the per-request envelope claim: the -* reserved protocol-version `_meta` key is present (regardless of whether the -* rest of the envelope is valid — validation is a separate, later step). -*/ -function src_CX2iR2pK_hasEnvelopeClaim(params) { - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; -} -/** -* The protocol version named by a message's envelope claim, when the claim is -* present and carries a string value. A present claim with a non-string value -* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a -* validation issue instead of a version. -*/ -function src_CX2iR2pK_envelopeClaimVersion(params) { - const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; - return typeof value === "string" ? value : void 0; -} -/** -* Validates a request's `_meta` object as a 2026-07-28 per-request envelope -* and reports problems as self-identifying issues (which key, what problem). -* -* Returns an empty array when the envelope is valid. Missing required keys are -* reported first (as `problem: 'missing'`), then schema violations inside -* present keys, in a stable order. -*/ -function src_CX2iR2pK_validateEnvelopeMeta(meta) { - return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); -} - -//#endregion -//#region ../core-internal/src/types/schemas.ts -var schemas_exports = /* @__PURE__ */ __exportAll({ - AnnotationsSchema: () => AnnotationsSchema, - AudioContentSchema: () => AudioContentSchema, - BaseMetadataSchema: () => BaseMetadataSchema, - BaseRequestParamsSchema: () => BaseRequestParamsSchema, - BlobResourceContentsSchema: () => BlobResourceContentsSchema, - BooleanSchemaSchema: () => BooleanSchemaSchema, - CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, - CallToolRequestSchema: () => CallToolRequestSchema, - CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, - CancelTaskRequestSchema: () => CancelTaskRequestSchema, - CancelTaskResultSchema: () => CancelTaskResultSchema, - CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, - CancelledNotificationSchema: () => CancelledNotificationSchema, - ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, - ClientNotificationSchema: () => ClientNotificationSchema, - ClientRequestSchema: () => ClientRequestSchema, - ClientResultSchema: () => ClientResultSchema, - ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, - CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, - CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, - CompleteRequestSchema: () => CompleteRequestSchema, - CompleteResultSchema: () => CompleteResultSchema, - ContentBlockSchema: () => ContentBlockSchema, - CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, - CreateMessageRequestSchema: () => CreateMessageRequestSchema, - CreateMessageResultSchema: () => CreateMessageResultSchema, - CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, - CreateTaskResultSchema: () => CreateTaskResultSchema, - CursorSchema: () => CursorSchema, - DiscoverRequestSchema: () => DiscoverRequestSchema, - DiscoverResultSchema: () => DiscoverResultSchema, - ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, - ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, - ElicitRequestSchema: () => ElicitRequestSchema, - ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, - ElicitResultSchema: () => ElicitResultSchema, - ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, - ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, - EmbeddedResourceSchema: () => EmbeddedResourceSchema, - EmptyResultSchema: () => EmptyResultSchema, - EnumSchemaSchema: () => EnumSchemaSchema, - GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, - GetPromptRequestSchema: () => GetPromptRequestSchema, - GetPromptResultSchema: () => GetPromptResultSchema, - GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, - GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, - GetTaskRequestSchema: () => GetTaskRequestSchema, - GetTaskResultSchema: () => GetTaskResultSchema, - IconSchema: () => IconSchema, - IconsSchema: () => IconsSchema, - ImageContentSchema: () => ImageContentSchema, - ImplementationSchema: () => ImplementationSchema, - InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, - InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, - InitializeResultSchema: () => InitializeResultSchema, - InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, - JSONArraySchema: () => JSONArraySchema, - JSONObjectSchema: () => JSONObjectSchema, - JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, - JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, - JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, - JSONRPCRequestSchema: () => JSONRPCRequestSchema, - JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, - JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, - JSONValueSchema: () => JSONValueSchema, - LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, - ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, - ListPromptsRequestSchema: () => ListPromptsRequestSchema, - ListPromptsResultSchema: () => ListPromptsResultSchema, - ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, - ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, - ListResourcesRequestSchema: () => ListResourcesRequestSchema, - ListResourcesResultSchema: () => ListResourcesResultSchema, - ListRootsRequestSchema: () => ListRootsRequestSchema, - ListRootsResultSchema: () => ListRootsResultSchema, - ListTasksRequestSchema: () => ListTasksRequestSchema, - ListTasksResultSchema: () => ListTasksResultSchema, - ListToolsRequestSchema: () => ListToolsRequestSchema, - ListToolsResultSchema: () => ListToolsResultSchema, - LoggingLevelSchema: () => LoggingLevelSchema, - LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, - LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, - ModelHintSchema: () => ModelHintSchema, - ModelPreferencesSchema: () => ModelPreferencesSchema, - MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, - NotificationSchema: () => NotificationSchema, - NotificationsParamsSchema: () => NotificationsParamsSchema, - NumberSchemaSchema: () => NumberSchemaSchema, - PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, - PaginatedRequestSchema: () => PaginatedRequestSchema, - PaginatedResultSchema: () => PaginatedResultSchema, - PingRequestSchema: () => PingRequestSchema, - PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, - ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, - ProgressNotificationSchema: () => ProgressNotificationSchema, - ProgressSchema: () => ProgressSchema, - ProgressTokenSchema: () => ProgressTokenSchema, - PromptArgumentSchema: () => PromptArgumentSchema, - PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, - PromptMessageSchema: () => PromptMessageSchema, - PromptReferenceSchema: () => PromptReferenceSchema, - PromptSchema: () => PromptSchema, - ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, - ReadResourceRequestSchema: () => ReadResourceRequestSchema, - ReadResourceResultSchema: () => ReadResourceResultSchema, - RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, - RequestIdSchema: () => RequestIdSchema, - RequestMetaSchema: () => RequestMetaSchema, - RequestSchema: () => RequestSchema, - ResourceContentsSchema: () => ResourceContentsSchema, - ResourceLinkSchema: () => ResourceLinkSchema, - ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, - ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, - ResourceSchema: () => ResourceSchema, - ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, - ResourceTemplateSchema: () => ResourceTemplateSchema, - ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, - ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, - ResultMetaObjectSchema: () => ResultMetaObjectSchema, - ResultSchema: () => ResultSchema, - RoleSchema: () => RoleSchema, - RootSchema: () => RootSchema, - RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, - SamplingContentSchema: () => SamplingContentSchema, - SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, - SamplingMessageSchema: () => SamplingMessageSchema, - ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, - ServerNotificationSchema: () => ServerNotificationSchema, - ServerRequestSchema: () => ServerRequestSchema, - ServerResultSchema: () => ServerResultSchema, - ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, - SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, - SetLevelRequestSchema: () => SetLevelRequestSchema, - SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, - StringSchemaSchema: () => StringSchemaSchema, - SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, - SubscribeRequestSchema: () => SubscribeRequestSchema, - SubscriptionFilterSchema: () => SubscriptionFilterSchema, - SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, - SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, - SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, - SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, - SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, - SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, - TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, - TaskCreationParamsSchema: () => TaskCreationParamsSchema, - TaskMetadataSchema: () => TaskMetadataSchema, - TaskSchema: () => TaskSchema, - TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, - TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, - TaskStatusSchema: () => TaskStatusSchema, - TextContentSchema: () => TextContentSchema, - TextResourceContentsSchema: () => TextResourceContentsSchema, - TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, - ToolAnnotationsSchema: () => ToolAnnotationsSchema, - ToolChoiceSchema: () => ToolChoiceSchema, - ToolExecutionSchema: () => ToolExecutionSchema, - ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, - ToolResultContentSchema: () => ToolResultContentSchema, - ToolSchema: () => ToolSchema, - ToolUseContentSchema: () => ToolUseContentSchema, - UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, - UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, - UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, - UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema -}); - -//#endregion -//#region ../core-internal/src/types/guards.ts -/** -* Validates and parses an unknown value as a JSON-RPC message. -* -* Use this to validate incoming messages in custom transport implementations. -* Throws if the value does not conform to the JSON-RPC message schema. -* -* @param value - The value to validate (typically a parsed JSON object). -* @returns The validated {@linkcode JSONRPCMessage}. -* @throws If validation fails. -*/ -function parseJSONRPCMessage(value) { - return JSONRPCMessageSchema.parse(value); -} -const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. -*/ -const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode CallToolResult}. -* -* This is a consumer-side VALUE check against the neutral model, not a wire -* validator: a raw wire object that additionally carries wire-only members -* (e.g. `resultType`) still passes through the loose index signature. Use a -* transport-level parse to validate raw wire traffic. -* -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. -*/ -const isCallToolResult = (value) => { - if (typeof value !== "object" || value === null || value.content === void 0) return false; - return CallToolResultSchema.safeParse(value).success; -}; -/** -* Checks whether a value is an input-required result (protocol revision -* 2026-07-28): the multi-round-trip return shape discriminated by -* `resultType: 'input_required'`. -* -* This is a discriminator check, not a full validator — the at-least-one rule -* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` -* builder and re-checked by the server seam for hand-built values. -* -* @param value - The value to check. -* @returns True if the value carries the `input_required` discriminator. -*/ -const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; -/** -* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. -* -* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK -* runtime; kept importable for interoperability only. -*/ -const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); -} - -//#endregion -//#region ../core-internal/src/shared/mcpParamHeaders.ts -/** The fixed prefix every custom-parameter header carries. */ -const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; -/** The schema-extension property name a tool's `inputSchema` carries. */ -const X_MCP_HEADER_KEY = "x-mcp-header"; -/** -* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control -* characters (including CR/LF), and the listed delimiters. -*/ -const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -/** -* JSON Schema `type` values the spec admits on an `x-mcp-header` property. -* -* The spec text names `integer`, `string`, `boolean` and explicitly excludes -* `number`. The published conformance referee at the pinned release ships its -* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` -* parameters and expects the client to mirror them, so `number` is accepted -* here so that the conformance gate passes; the discrepancy is tracked -* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. -*/ -const PERMITTED_X_MCP_HEADER_TYPES = new Set([ - "string", - "integer", - "boolean", - "number" -]); -/** -* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations -* and validate every constraint the spec places on them. Returns either the -* collected declarations (possibly empty) or the first violated constraint. -* -* The walk descends through `properties` at any depth (the spec's "any nesting -* depth" clause). The static-reachability MUST is enforced as a structural -* sweep: every position the chain MUST NOT pass through (`items`/ -* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, -* `$defs`, `$ref` targets within `$defs`) is visited too, and an -* `x-mcp-header` found anywhere on that path invalidates the schema — "an -* annotation anywhere else makes the tool definition invalid". -*/ -function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { - const declarations = []; - const seenLower = /* @__PURE__ */ new Map(); - const visit = (node, path, reachable) => { - if (node === null || typeof node !== "object") return void 0; - const schema = node; - if (X_MCP_HEADER_KEY in schema) { - if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; - const raw = schema[X_MCP_HEADER_KEY]; - if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; - if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; - const type = typeof schema.type === "string" ? schema.type : void 0; - if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; - const lower = raw.toLowerCase(); - const prior = seenLower.get(lower); - if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; - seenLower.set(lower, raw); - declarations.push({ - path, - headerName: raw, - type - }); - } - const properties = schema.properties; - if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { - const fault$1 = visit(child, [...path, key], reachable); - if (fault$1 !== void 0) return fault$1; - } - for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { - const sub = schema[k]; - if (sub === void 0) continue; - const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; - for (const branch of branches) { - const fault$1 = visit(branch, [...path, `<${k}>`], false); - if (fault$1 !== void 0) return fault$1; - } - } - }; - const fault = visit(inputSchema, [], true); - return fault === void 0 ? { - valid: true, - declarations - } : { - valid: false, - reason: fault - }; -} -/** -* JSON Schema keywords whose subschemas the SEP-2243 static-reachability -* constraint excludes from the `properties`-only chain. An `x-mcp-header` -* found under any of these invalidates the tool definition. -*/ -const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions" -]; -/** -* Subschema-carrying keywords whose value is a `name → subschema` object -* (not a single subschema or array of subschemas). The visit branches over -* `Object.values()` for these. -*/ -const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ - "patternProperties", - "dependentSchemas", - "$defs", - "definitions" -]); -function pathName(path) { - return path.length === 0 ? "" : path.join("."); -} -const BASE64_SENTINEL_PREFIX = "=?base64?"; -const BASE64_SENTINEL_SUFFIX = "?="; -const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; -const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; -/** -* Convert a primitive argument value to its string representation per the -* spec's type-conversion rules: strings pass through, integers and numbers -* become their decimal string, booleans become lowercase `'true'` / `'false'`. -* Non-finite numbers and integers outside the safe range are refused (the -* caller treats `undefined` as "do not emit a header for this value"). -*/ -function mcpParamPrimitiveToString(value) { - if (typeof value === "string") return value; - if (typeof value === "boolean") return value ? "true" : "false"; - if (typeof value === "number") { - if (!Number.isFinite(value)) return void 0; - if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; - return String(value); - } -} -function base64ToUtf8(b64) { - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return new TextDecoder("utf-8", { fatal: true }).decode(bytes); -} -/** -* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, -* the payload is decoded as UTF-8; otherwise the value is returned as-is. -* Returns `undefined` when the sentinel is present but the payload is not -* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject -* such values. -*/ -function decodeMcpParamValue(value) { - if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; - const b64 = value.slice(9, value.length - 2); - if (!BASE64_CANONICAL.test(b64)) return void 0; - try { - return base64ToUtf8(b64); - } catch { - return; - } -} -function valueAtPath(root, path) { - let node = root; - for (const key of path) { - if (node === null || typeof node !== "object") return void 0; - node = node[key]; - } - return node; -} -/** -* The header/body comparison the server performs at tool-resolution time. -* -* For each `x-mcp-header` declaration on the named tool: when the body -* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be -* present and decode to an equal value; when the body value is `null` or -* absent the server MUST NOT expect the header (a present header is ignored). -* A sentinel-carrying header whose payload is not canonical Base64 / valid -* UTF-8 is rejected as invalid characters. -* -* Integer-typed declarations are compared numerically (the spec's SHOULD — -* `42.0` and `42` are equal); everything else is compared as decoded strings. -* -* Returns `undefined` when every check passes, or an -* {@linkcode InboundLadderRejection} carrying the same `-32020` -* (`HeaderMismatch`) shape the inbound classifier emits for the -* standard-header cross-checks — `400 Bad Request` with the disagreeing pair -* in `data.mismatch`. -*/ -function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { - for (const decl of declarations) { - const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; - const headerValue = headers.get(headerKey); - const bodyRaw = valueAtPath(args, decl.path); - if (bodyRaw === void 0 || bodyRaw === null) continue; - const bodyString = mcpParamPrimitiveToString(bodyRaw); - if (bodyString === void 0) continue; - if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); - const decoded = decodeMcpParamValue(headerValue); - if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); - if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); - } -} -/** -* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` -* disagreement. Same shape as the inbound classifier's standard-header -* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing -* pair, `settled: true`); only the rung differs because this check runs at the -* pre-dispatch step against a known tool's schema rather than at the edge. -*/ -function paramHeaderMismatchRejection(cell, header, body) { - return { - kind: "reject", - rung: "param-header-validation", - cell, - httpStatus: 400, - code: HEADER_MISMATCH_ERROR_CODE, - message: `Bad Request: the request headers and body disagree: ${body}`, - data: { mismatch: { - header, - body - } }, - settled: true - }; -} - -//#endregion -//#region ../core-internal/src/shared/inboundClassification.ts -/** -* Inbound HTTP request classification and the inbound validation ladder -* (protocol revision 2026-07-28). -* -* `classifyInboundRequest` is the body-primary era predicate for an HTTP -* entry that serves both protocol eras on one endpoint. It is evaluated -* exactly once, at the entry boundary, on the already-parsed request body: -* -* - `initialize` is a legacy-era request by definition (the modern era has no -* `initialize` handshake) — unless it carries a valid envelope claim naming -* a modern revision, in which case the claim wins and the request is -* classified like any other enveloped request (the modern era then answers -* it with method-not-found, exactly like every other method it does not -* define). -* - A request whose `params._meta` carries the reserved protocol-version key -* claims the per-request envelope mechanism and classifies into the era the -* named revision belongs to (a malformed envelope behind a present claim is -* a validation error, never a silent fall back to legacy handling). -* - A request without a claim is legacy-era traffic. -* - The `MCP-Protocol-Version` header is a cross-check only: it never -* upgrades or downgrades a body-derived classification, and a disagreement -* between header and body is an explicit ladder outcome. -* - Notifications carry no envelope claim of their own under the current -* spec, so for notification POSTs without a body claim the modern header is -* determinative; the `Mcp-Method` header is validated against the body when -* the message classifies modern and is never enforced on legacy traffic. -* A notification that does carry a claim is treated body-primary like a -* request, and a malformed claim is rejected the same way a request's -* malformed claim is — never silently resolved against the header. -* The notification-POST header cross-checks here are an SDK-defensive -* posture, not a spec requirement: the spec leaves header rules for posted -* notifications undefined (core client notifications do not occur over -* Streamable HTTP); applying the request rules symmetrically is what an -* ecosystem custom-notification POST expects, and the −32020 cells stay -* passing for them. -* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era -* session operations: the modern era is `POST`-only, so they are routed to -* legacy serving when it is configured and rejected otherwise. -* - Array (batch) bodies are classified element-wise: an array containing a -* modern-claiming or invalid element is rejected, an all-legacy array is -* legacy traffic unchanged, and a single-element array is still an array. -* -* The classifier returns plain values (it never throws and never touches a -* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection -* carrying the JSON-RPC error to emit and the HTTP status to emit it with. -* Legacy routing outcomes deliberately carry NO `MessageClassification` — -* legacy and hand-wired traffic is never classified, which keeps its -* dispatch behavior byte-identical to today's. -* -* Error codes for the modern-path rejection cells follow the published -* conformance suite (and the spec text it asserts): -* -* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header -* disagreeing with the body, or the `Mcp-Method` header disagreeing with the -* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. -* - A request whose protocol-version header names a modern revision but whose -* body carries no `_meta` envelope claim — including an envelope present but -* missing the required protocol-version key — is rejected with `-32602` -* (invalid params) naming the missing key(s), on HTTP 400. -* -* Should a future spec revision or conformance release change these -* assignments, the affected cells are re-derived against that release; the -* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark -* a cell provisional again while such a change is in flight. -*/ -/** -* The error code emitted for header/body cross-check mismatches: the -* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or -* with the body's classification), and the `Mcp-Method` header disagreeing -* with the body method. -* -* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 -* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted -* by the published conformance suite for header-validation failures. It has no -* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era -* wire vocabulary; the validation ladder is its only emitter. -*/ -const HEADER_MISMATCH_ERROR_CODE = -32020; -/** -* The inbound validation ladder, expressed as data rather than control flow. -* -* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the -* dispatch rungs are evaluated by the protocol layer once the classified -* message is injected into a per-request server instance (the era registry -* gate, the envelope requiredness check, and per-method params validation). -* The client-capability rung is evaluated by the HTTP entry itself, -* pre-dispatch, on the validated envelope the classifier produced — see that -* rung's rationale for the ordering caveat. The order is the precedence: a -* request that fails several rungs is answered by the earliest one. -*/ -const INBOUND_VALIDATION_LADDER = [ - { - rung: "http-method", - order: 1, - evaluatedAt: "edge", - codes: [-32e3], - conformance: [], - rationale: "The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read." - }, - { - rung: "jsonrpc-shape", - order: 2, - evaluatedAt: "edge", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest], - conformance: ["server-stateless"], - rationale: "The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic." - }, - { - rung: "era-classification", - order: 3, - evaluatedAt: "edge", - codes: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion], - conformance: [ - "server-stateless", - "http-header-validation", - "http-custom-header-server-validation" - ], - rationale: "Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions." - }, - { - rung: "envelope", - order: 4, - evaluatedAt: "edge", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: ["server-stateless"], - rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." - }, - { - rung: "method-registry", - order: 5, - evaluatedAt: "dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], - conformance: ["server-stateless"], - rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." - }, - { - rung: "request-params", - order: 6, - evaluatedAt: "dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: [], - rationale: "Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table." - }, - { - rung: "standard-header-validation", - order: 7, - evaluatedAt: "pre-dispatch", - codes: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-header-validation"], - rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted." - }, - { - rung: "client-capabilities", - order: 8, - evaluatedAt: "pre-dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], - conformance: ["server-stateless"], - rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." - }, - { - rung: "param-header-validation", - order: 9, - evaluatedAt: "pre-dispatch", - codes: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-custom-header-server-validation"], - rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." - } -]; -/** -* HTTP status for ladder-originated JSON-RPC error codes. -* -* Keyed on origin, not on the bare code: this table only applies to errors -* the ladder (or a pre-handler protocol gate) produced. Errors produced by -* request handlers — whatever their code — stay in-band on HTTP 200, and are -* never mapped to an HTTP status by this table; in particular `-32603` and -* domain-specific codes never become a blanket 500. The single exception is -* `MissingRequiredClientCapability` (-32021) — see -* {@linkcode httpStatusForErrorCode}. -* -* `-32602` (invalid params) deliberately has NO entry: the only invalid-params -* rejection that maps to HTTP 400 is the classifier's own envelope rung -* short-circuit, which carries its HTTP status directly. A dispatch- or -* handler-produced invalid-params error is always in-band. -*/ -const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { - [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, - [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, - [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, - [HEADER_MISMATCH_ERROR_CODE]: 400 -}; -/** -* The HTTP status to answer a JSON-RPC error with, keyed on the error's -* origin. `in-band` errors (anything produced by a request handler) are -* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP -* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), -* whose 400 the spec mandates on the error itself with no origin condition, -* and which the SDK genuinely produces after dispatch (the `input_required` -* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` -* is NOT that peer's spec error and stays in-band like every other handler -* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. -* -* The per-request transport intentionally does NOT delegate to this function: -* its `?? 400` ladder fallback is only correct for entry-gate codes known to -* the table, and would wrongly map dispatch-window errors outside it (a -* window `-32602` must stay in-band on 200). The transport indexes the table -* directly; keep the two in agreement when editing either. -*/ -function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { - if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; - return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; -} -function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { - return { - kind: "reject", - rung, - cell, - httpStatus, - code: error.code, - message: error.message, - ...error.data !== void 0 && { data: error.data }, - settled - }; -} -function crossCheckMismatch(cell, header, body, rung = "era-classification") { - return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { - header, - body - } }), true); -} -/** -* The methods whose body carries a `params.name` / `params.uri` value the -* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 -* § Standard Request Headers, `Required For` column). -*/ -const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ - "tools/call": "name", - "prompts/get": "name", - "resources/read": "uri" -})); -/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ -function stripHttpOws(value) { - let start = 0; - while (start < value.length) { - const code = value.codePointAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - let end = value.length; - while (end > start) { - const code = value.codePointAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === value.length ? value : value.slice(start, end); -} -/** -* SEP-2243 standard-header server-side validation, evaluated by the HTTP -* entry on a modern-classified request immediately after -* {@linkcode classifyInboundRequest} returns a modern route. -* -* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, -* `standard-header-validation` rung — the same shape -* {@linkcode classifyInboundRequest} already emits on the edge -* `era-classification` rung for the `MCP-Protocol-Version` and -* `Mcp-Method` *mismatch* cells) when: -* -* - the required `Mcp-Method` header is absent; -* - the required `Mcp-Name` header is absent on a `tools/call`, -* `prompts/get`, or `resources/read` request whose body carries the -* `params.name` / `params.uri` value the header mirrors; -* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or -* - the (decoded) `Mcp-Name` value disagrees with the body's -* `params.name` / `params.uri`. -* -* Returns `undefined` (pass) for notifications (the spec table reads -* "All requests"), for methods that have no `Mcp-Name` source, and when the -* headers agree with the body. Never enforced on legacy traffic — the entry -* only calls this on a modern route. -* -* Kept separate from {@linkcode classifyInboundRequest} so that a body-only -* call to the classifier (no headers passed) keeps routing a modern request -* unchanged: the classifier remains a pure body-primary router, and this -* function is the presence/`Mcp-Name` half of the standard-header rung the -* entry layers on top. -*/ -function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { - if (route.messageKind !== "request") return; - const method = route.message.method; - if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); - const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; - if (sourceField === void 0) return; - const sourceValue = route.message.params?.[sourceField]; - const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; - if (request.mcpNameHeader === void 0) { - if (bodyValue === void 0) return; - return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); - } - const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); - const decoded = decodeMcpParamValue(normalizedNameHeader); - if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); - if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); -} -function isPlainObject$2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function classificationForClaim(claimedVersion) { - if (claimedVersion === void 0) return { era: "modern" }; - return { - era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", - revision: claimedVersion - }; -} -/** -* Whether a request's params carry a per-request envelope claim that is both -* well-formed and names a modern protocol revision. -* -* Used by the `initialize` precedence rule: only such a claim overrides the -* `initialize` ⇒ legacy-handshake classification — a request carrying a valid -* modern envelope is a modern request regardless of its method name, and the -* modern era then answers `initialize` exactly like any other method it does -* not define (method-not-found). A malformed claim, or one naming a pre-2026 -* revision, keeps the legacy-handshake routing unchanged. -* -* Exported on the core internal barrel for the stdio serving entry, which -* applies the same precedence rule to a connection's opening message; not -* public API. -*/ -function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { - if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; -} -function classifyBatch(body) { - if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); - for (const element of body) { - if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); - if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); - } - return { - kind: "legacy", - reason: "batch" - }; -} -function classifyRequestBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { - if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); - const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "request", - message: body, - classification: classificationForClaim(claimedVersion) - }; - } - if (headerNamesModern) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); - const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; - return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); - } - return { - kind: "legacy", - reason: "no-claim", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -function classifyNotificationBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { - key: PROTOCOL_VERSION_META_KEY, - problem: "expected a protocol version string" - }; - return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); - } - if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - const classification = classificationForClaim(claimedVersion); - if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification - }; - } - if (headerNamesModern) { - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification: { - era: "modern", - revision: headerVersion - } - }; - } - return { - kind: "legacy", - reason: "notification", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -/** -* Classifies one inbound HTTP request for dual-era serving. -* -* The body-primary predicate, evaluated once at the entry boundary: see the -* module documentation for the rules. Returns a routing outcome (`legacy` or -* `modern`) or a ladder rejection; it never throws. -*/ -function src_CX2iR2pK_classifyInboundRequest(request) { - request = { - ...request, - ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, - ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, - ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } - }; - if (request.httpMethod.toUpperCase() !== "POST") return { - kind: "legacy", - reason: "http-method" - }; - const body = request.body; - if (Array.isArray(body)) return classifyBatch(body); - if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { - kind: "legacy", - reason: "response" - }; - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); - return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); -} -/** -* The rejection a modern-only endpoint (no legacy serving configured) -* answers a legacy-classified request with. -* -* - Envelope-less requests (including `initialize`) are answered with the -* unsupported-protocol-version error carrying the endpoint's supported -* versions and echoing the version the request named (when it named one — -* `requested` is omitted rather than fabricated when the request named no -* version at all), so a legacy client can discover what the endpoint serves -* from the error alone. -* - Posted responses and batch arrays are invalid requests on the modern era. -* - Non-`POST` methods are not allowed. -* - Legacy-classified notifications return `undefined`: the caller answers -* 202 with no body and does not dispatch the notification (accept-and-drop). -*/ -function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { - switch (route.reason) { - case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); - case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); - case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); - case "notification": return; - case "initialize": - case "no-claim": { - const requested = route.requestedVersion; - return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: [...supportedVersions], - requested - }), true); - } - } -} - -//#endregion -//#region ../core-internal/src/util/schema.ts -/** -* Internal Zod schema utilities for protocol handling. -* These are used internally by the SDK for protocol message validation. -*/ -/** -* Parses data against a Zod schema (synchronous). -* Returns a discriminated union with success/error. -*/ -function parseSchema(schema, data) { - return parse_safeParse(schema, data); -} -/** -* Union of the declared shape keys across several Zod object schemas. -*/ -function shapeKeys(schemas) { - return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); -} - -//#endregion -//#region ../core-internal/src/util/standardSchema.ts -/** -* Standard Schema utilities for user-provided schemas. -* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. -* @see https://standardschema.dev -*/ -function isStandardSchema(schema) { - if (schema == null) return false; - const schemaType = typeof schema; - if (schemaType !== "object" && schemaType !== "function") return false; - if (!("~standard" in schema)) return false; - return typeof schema["~standard"]?.validate === "function"; -} -let warnedZodFallback = false; -/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ -const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; -/** -* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. -* -* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt -* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). -* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, -* so for `io: 'input'` this function defaults `type` to `"object"` when absent -* and throws on an explicit non-object `type` (e.g. `z.string()`). For -* `io: 'output'` a non-object root is returned as-is; the `"object"` default is -* applied only when the root is provably object-shaped. -*/ -function standardSchemaToJsonSchema(schema, io = "input") { - const std = schema["~standard"]; - let result; - if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); - else if (std.vendor === "zod") { - if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema()."); - if (!warnedZodFallback) { - warnedZodFallback = true; - console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning."); - } - result = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io - }); - } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); - if (io === "output") { - if (result.type !== void 0) return result; - return isProvablyObjectShapedRoot(result) ? { - type: "object", - ...result - } : result; - } - if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); - return { - type: "object", - ...result - }; -} -/** -* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords -* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a -* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively -* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to -* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. -*/ -function isProvablyObjectShapedRoot(schema) { - if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; - for (const key of [ - "oneOf", - "anyOf", - "allOf" - ]) { - const members = schema[key]; - if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); - } - return false; -} -function formatIssue(issue) { - if (!issue.path?.length) return issue.message; - return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; -} -async function validateStandardSchema(schema, data) { - const result = await schema["~standard"].validate(data); - if (result.issues && result.issues.length > 0) return { - success: false, - error: result.issues.map((i) => formatIssue(i)).join(", ") - }; - return { - success: true, - data: result.value - }; -} -function zodEmittedPattern(schema) { - const jsonSchema = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io: "input" - }); - return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; -} -const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; -function datetimeReferenceSchemas(pattern) { - const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); - const precisions = [ - void 0, - -1, - 0 - ]; - if (fractionDigits) precisions.push(Number(fractionDigits[1])); - return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ - local, - offset, - precision - })))); -} -function referencePatternsForFormat(format, pattern) { - let referenceSchemas; - switch (format) { - case "email": - referenceSchemas = [schemas_email()]; - break; - case "uri": - referenceSchemas = [schemas_url()]; - break; - case "date": - referenceSchemas = [iso_date()]; - break; - case "date-time": - referenceSchemas = datetimeReferenceSchemas(pattern); - break; - } - return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); -} -/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ -function isLibraryFormatPattern(format, pattern, vendor) { - if (vendor !== "zod") return true; - return referencePatternsForFormat(format, pattern).has(pattern); -} -function promptArgumentsFromStandardSchema(schema) { - const jsonSchema = standardSchemaToJsonSchema(schema, "input"); - const properties = jsonSchema.properties || {}; - const required = jsonSchema.required || []; - return Object.entries(properties).map(([name, prop]) => ({ - name, - description: prop?.description, - required: required.includes(name) - })); -} - -//#endregion -//#region ../core-internal/src/shared/elicitation.ts -function isJsonObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function convertStandardElicitationSchema(schema) { - try { - return standardSchemaToJsonSchema(schema, "input"); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); - } -} -const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ - "$comment", - "deprecated", - "description", - "examples", - "readOnly", - "title", - "writeOnly" -]); -function isAnnotationOnlyJsonSchemaKeyword(key) { - return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); -} -const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); -const PROPERTY_KEYS_BY_TYPE = { - string: shapeKeys([ - StringSchemaSchema, - UntitledSingleSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema, - LegacyTitledEnumSchemaSchema - ]), - number: shapeKeys([NumberSchemaSchema]), - integer: shapeKeys([NumberSchemaSchema]), - boolean: shapeKeys([BooleanSchemaSchema]), - array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) -}; -const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); -/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ -function walkProperty(node, path, vendor, unsupported) { - if (!isJsonObject(node)) return node; - const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; - if (allowedKeys === void 0) return node; - const pruned = {}; - for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; - else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { - if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; - else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); - } else unsupported.push(`${path}.${key}`); - return pruned; -} -/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ -function walkRequestedSchema(converted, vendor) { - const pruned = {}; - const unsupported = []; - for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); - else if (ROOT_KEYS.has(key)) pruned[key] = value; - else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); - if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); - return pruned; -} -/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ -function describeUnsupportedProperties(pruned, fallback) { - if (!isJsonObject(pruned.properties)) return fallback; - const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); - return offenders.length > 0 ? offenders.join(", ") : fallback; -} -function findDroppedConstraintPaths(original, parsed, path = "") { - if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); - if (!isJsonObject(original) || !isJsonObject(parsed)) return []; - return Object.entries(original).flatMap(([key, value]) => { - const childPath = path ? `${path}.${key}` : key; - if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; - return findDroppedConstraintPaths(value, parsed[key], childPath); - }); -} -/** Converts an authoring-friendly elicitation input into its wire-ready form. */ -function normalizeElicitInputParams(input) { - if (!isStandardSchema(input.requestedSchema)) return { - ...input, - mode: "form", - requestedSchema: input.requestedSchema - }; - const vendor = input.requestedSchema["~standard"].vendor; - const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); - const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); - const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); - if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); - const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); - if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); - return { - ...input, - mode: "form", - requestedSchema: parsed.data - }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequired.ts -/** -* Authoring helpers for multi-round-trip requests (protocol revision -* 2026-07-28). -* -* A handler for one of the multi-round-trip methods (`tools/call`, -* `prompts/get`, `resources/read`) requests additional client input by -* returning an {@linkcode InputRequiredResult} instead of a final result. The -* helpers here build that return value and its embedded requests as NEUTRAL -* values; only the 2026-07-28 wire codec maps them to/from the wire. The -* 2025-era codec has no input-required vocabulary — on a 2025-era request the -* server's legacy shim (on by default) fulfils the embedded requests as real -* server→client requests and re-enters the handler, so the same return shape -* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores -* the pre-shim loud failure. -* -* There is no nominal brand: `resultType: 'input_required'` is the -* discriminator, and hand-built result literals are equally legal — the -* server seam re-checks the at-least-one rule for them. -*/ -function buildInputRequired(spec) { - const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; - const hasRequestState = typeof spec.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)"); - return { - resultType: "input_required", - ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, - ...spec.requestState !== void 0 && { requestState: spec.requestState } - }; -} -/** -* Builder for the input-required return value of multi-round-trip handlers, -* with per-kind constructors for the embedded requests -* (`inputRequired.elicit`, `inputRequired.elicitUrl`, -* `inputRequired.createMessage`, `inputRequired.listRoots`). -* -* @example Write-once tool requesting confirmation -* ```ts -* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { -* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); -* if (!confirmed) { -* return inputRequired({ -* inputRequests: { -* confirm: inputRequired.elicit({ -* message: `Deploy to ${env}?`, -* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } -* }) -* } -* }); -* } -* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; -* }); -* ``` -*/ -const inputRequired = Object.assign(buildInputRequired, { - elicit(params) { - try { - return { - method: "elicitation/create", - params: normalizeElicitInputParams(params) - }; - } catch (error) { - throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; - } - }, - elicitUrl(params) { - return { - method: "elicitation/create", - params: { - ...params, - mode: "url" - } - }; - }, - createMessage(params) { - return { - method: "sampling/createMessage", - params - }; - }, - listRoots() { - return { method: "roots/list" }; - } -}); -function acceptedContent(responses, key, schema) { - const view = inputResponse(responses, key); - if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; - if (schema === void 0) return view.content; - const outcome = schema["~standard"].validate(view.content); - if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); - return outcome.issues === void 0 ? outcome.value : void 0; -} -/** -* Reads one entry of a retried request's `inputResponses` -* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering -* decline/cancel detection and the non-elicitation response kinds that -* {@linkcode acceptedContent} does not surface. -* -* The values arrive from the client and are not re-validated here — treat -* them as untrusted input (validate elicitation content with the -* schema-aware {@linkcode acceptedContent} overload where it matters). -*/ -function inputResponse(responses, key) { - if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; - const entry = responses[key]; - if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; - const candidate = entry; - if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { - const content = candidate["content"]; - return { - kind: "elicit", - action: candidate["action"], - ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } - }; - } - if (Array.isArray(candidate["roots"])) return { - kind: "roots", - roots: candidate["roots"] - }; - if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { - kind: "sampling", - result: candidate - }; - return { kind: "missing" }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredDriver.ts -/** -* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). -* -* When a request to one of the multi-round-trip methods comes back as -* `input_required`, the driver fulfils the embedded input requests by -* dispatching them to the client's already-registered handlers (elicitation, -* sampling, roots — one generic engine, no per-feature API), then retries the -* original request with the collected `inputResponses` and a byte-exact echo -* of `requestState`, on a fresh request id, until the server returns a -* complete result or the round cap is exhausted. -* -* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the -* same primitive a manual caller uses (`allowInputRequired` semantics — the -* retry hands back the next `input_required` payload instead of recursing), -* so the loop, the cap, and the pacing live in one place and disabling -* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this -* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to -* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by -* shrinking the budget passed to each leg — no new timer system. -*/ -/** -* Fixed pacing applied before retrying a requestState-only (load-shedding) -* leg — a leg that carries no embedded input requests, so nothing slows the -* loop down naturally. Counted in the same round cap. -*/ -const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; -/** -* The message both multi-round-trip loops emit when the round cap is -* exhausted — the client driver as a typed error, the server-side legacy -* shim as its per-family failure. One formatter so the texts cannot drift -* (hosts and models read the tool-result copy verbatim). -*/ -function inputRequiredRoundsExceededMessage(method, maxRounds) { - return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; -} -/** -* Abortable delay: resolves after `ms`, or rejects with the signal's reason -* (wrapped in an `SdkError` when it isn't already one) if the signal aborts -* first. Aborting after resolution is a no-op. Shared with the server-side -* legacy shim (the pacing semantics must match per era). -*/ -function sleep(ms, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); - return; - } - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} -/** -* A per-round abort linked to the caller's signal: the embedded sibling -* dispatches share it, so the first failure (or a caller abort) cancels the -* others instead of leaving them running. Shared with the server-side legacy -* shim (the abort-linkage semantics must match per era). -*/ -function linkedRoundAbort(outer) { - const controller = new AbortController(); - const onOuterAbort = () => controller.abort(outer?.reason); - outer?.addEventListener("abort", onOuterAbort, { once: true }); - if (outer?.aborted) controller.abort(outer.reason); - return { - signal: controller.signal, - abort: (reason) => controller.abort(reason), - dispose: () => outer?.removeEventListener("abort", onOuterAbort) - }; -} - -//#endregion -//#region ../core-internal/src/types/specTypeSchema.ts -/** -* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. -* -* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no -* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, -* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). -* Keeping the list explicit means new public spec types must be added here deliberately, and -* internals never leak into `SpecTypeName`. -* -* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` -* (the bare name collides with the server package's `ResourceTemplate` class), so -* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to -* a type literally named `ResourceTemplate`. -*/ -const SPEC_SCHEMA_KEYS = [ - "AnnotationsSchema", - "AudioContentSchema", - "BaseMetadataSchema", - "BlobResourceContentsSchema", - "BooleanSchemaSchema", - "CallToolRequestSchema", - "CallToolRequestParamsSchema", - "CallToolResultSchema", - "CancelledNotificationSchema", - "CancelledNotificationParamsSchema", - "CancelTaskRequestSchema", - "CancelTaskResultSchema", - "ClientCapabilitiesSchema", - "ClientNotificationSchema", - "ClientRequestSchema", - "ClientResultSchema", - "CompatibilityCallToolResultSchema", - "CompleteRequestSchema", - "CompleteRequestParamsSchema", - "CompleteResultSchema", - "ContentBlockSchema", - "CreateMessageRequestSchema", - "CreateMessageRequestParamsSchema", - "CreateMessageResultSchema", - "CreateMessageResultWithToolsSchema", - "CreateTaskResultSchema", - "CursorSchema", - "DiscoverRequestSchema", - "DiscoverResultSchema", - "ElicitationCompleteNotificationSchema", - "ElicitationCompleteNotificationParamsSchema", - "ElicitRequestSchema", - "ElicitRequestFormParamsSchema", - "ElicitRequestParamsSchema", - "ElicitRequestURLParamsSchema", - "ElicitResultSchema", - "EmbeddedResourceSchema", - "EmptyResultSchema", - "EnumSchemaSchema", - "GetPromptRequestSchema", - "GetPromptRequestParamsSchema", - "GetPromptResultSchema", - "GetTaskPayloadRequestSchema", - "GetTaskPayloadResultSchema", - "GetTaskRequestSchema", - "GetTaskResultSchema", - "IconSchema", - "IconsSchema", - "ImageContentSchema", - "ImplementationSchema", - "InitializedNotificationSchema", - "InitializeRequestSchema", - "InitializeRequestParamsSchema", - "InitializeResultSchema", - "JSONArraySchema", - "JSONObjectSchema", - "JSONRPCErrorResponseSchema", - "JSONRPCMessageSchema", - "JSONRPCNotificationSchema", - "JSONRPCRequestSchema", - "JSONRPCResponseSchema", - "JSONRPCResultResponseSchema", - "JSONValueSchema", - "LegacyTitledEnumSchemaSchema", - "ListPromptsRequestSchema", - "ListPromptsResultSchema", - "ListResourcesRequestSchema", - "ListResourcesResultSchema", - "ListResourceTemplatesRequestSchema", - "ListResourceTemplatesResultSchema", - "ListRootsRequestSchema", - "ListRootsResultSchema", - "ListTasksRequestSchema", - "ListTasksResultSchema", - "ListToolsRequestSchema", - "ListToolsResultSchema", - "LoggingLevelSchema", - "LoggingMessageNotificationSchema", - "LoggingMessageNotificationParamsSchema", - "ModelHintSchema", - "ModelPreferencesSchema", - "MultiSelectEnumSchemaSchema", - "NotificationSchema", - "NumberSchemaSchema", - "PaginatedRequestSchema", - "PaginatedRequestParamsSchema", - "PaginatedResultSchema", - "PingRequestSchema", - "PrimitiveSchemaDefinitionSchema", - "ProgressSchema", - "ProgressNotificationSchema", - "ProgressNotificationParamsSchema", - "ProgressTokenSchema", - "PromptSchema", - "PromptArgumentSchema", - "PromptListChangedNotificationSchema", - "PromptMessageSchema", - "PromptReferenceSchema", - "ReadResourceRequestSchema", - "ReadResourceRequestParamsSchema", - "ReadResourceResultSchema", - "RelatedTaskMetadataSchema", - "RequestSchema", - "RequestIdSchema", - "RequestMetaSchema", - "ResourceSchema", - "ResourceContentsSchema", - "ResourceLinkSchema", - "ResourceListChangedNotificationSchema", - "ResourceRequestParamsSchema", - "ResourceTemplateSchema", - "ResourceTemplateReferenceSchema", - "ResourceUpdatedNotificationSchema", - "ResourceUpdatedNotificationParamsSchema", - "ResultMetaObjectSchema", - "ResultSchema", - "RoleSchema", - "RootSchema", - "RootsListChangedNotificationSchema", - "SamplingContentSchema", - "SamplingMessageSchema", - "SamplingMessageContentBlockSchema", - "ServerCapabilitiesSchema", - "ServerNotificationSchema", - "ServerRequestSchema", - "ServerResultSchema", - "SetLevelRequestSchema", - "SetLevelRequestParamsSchema", - "SingleSelectEnumSchemaSchema", - "StringSchemaSchema", - "SubscribeRequestSchema", - "SubscribeRequestParamsSchema", - "SubscriptionFilterSchema", - "SubscriptionsAcknowledgedNotificationSchema", - "SubscriptionsAcknowledgedNotificationParamsSchema", - "SubscriptionsListenRequestSchema", - "SubscriptionsListenRequestParamsSchema", - "SubscriptionsListenResultSchema", - "SubscriptionsListenResultMetaSchema", - "TaskAugmentedRequestParamsSchema", - "TaskCreationParamsSchema", - "TaskMetadataSchema", - "TaskSchema", - "TaskStatusSchema", - "TaskStatusNotificationSchema", - "TaskStatusNotificationParamsSchema", - "TextContentSchema", - "TextResourceContentsSchema", - "TitledMultiSelectEnumSchemaSchema", - "TitledSingleSelectEnumSchemaSchema", - "ToolSchema", - "ToolAnnotationsSchema", - "ToolChoiceSchema", - "ToolExecutionSchema", - "ToolListChangedNotificationSchema", - "ToolResultContentSchema", - "ToolUseContentSchema", - "UnsubscribeRequestSchema", - "UnsubscribeRequestParamsSchema", - "UntitledMultiSelectEnumSchemaSchema", - "UntitledSingleSelectEnumSchemaSchema" -]; -const authSchemas = { - IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, - OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, - OAuthClientInformationSchema: OAuthClientInformationSchema, - OAuthClientMetadataSchema: OAuthClientMetadataSchema, - OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, - OAuthErrorResponseSchema: OAuthErrorResponseSchema, - OAuthMetadataSchema: OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, - OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, - OAuthTokensSchema: OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, - OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema -}; -const _specTypeSchemas = {}; -const _isSpecType = {}; -function register(key, schema) { - const name = key.slice(0, -6); - _specTypeSchemas[name] = schema; - _isSpecType[name] = (v) => schema.safeParse(v).success; -} -for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); -for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); -/** -* Runtime validators for every MCP spec type, keyed by type name. -* -* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for -* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from -* storage that should be a `Tool`. -* -* Each entry implements the Standard Schema interface, so it composes with any -* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" -* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); -* if (result.issues === undefined) { -* // result.value is CallToolResult -* } -* ``` -*/ -const specTypeSchemas = Object.freeze(_specTypeSchemas); -/** -* Type predicates for every MCP spec type, keyed by type name. -* -* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and -* transforms are applied), and narrows to that input type. For schemas with `.default()` or -* `.preprocess()`, this may accept values that do not structurally match the named output type; -* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use -* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. -* -* Each guard is a standalone function, so it can be passed directly as a callback. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" -* if (isSpecType.ContentBlock(value)) { -* // value is ContentBlock -* } -* -* const blocks = mixed.filter(isSpecType.ContentBlock); -* ``` -*/ -const isSpecType = Object.freeze(_isSpecType); - -//#endregion -//#region ../core-internal/src/wire/bootstrap.ts -function bootstrapOutboundCodec(method) { - switch (method) { - case "initialize": - case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); - case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); - default: return; - } -} - -//#endregion -//#region ../core-internal/src/shared/protocol.ts -/** -* The default request timeout, in milliseconds. -*/ -const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; -/** -* The reserved per-request `_meta` envelope keys (protocol revision -* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before -* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are -* wire-level bookkeeping, not handler material. -*/ -const RESERVED_ENVELOPE_META_KEYS = [ - auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, - auth_CUe6YdwF_CLIENT_INFO_META_KEY, - auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, - LOG_LEVEL_META_KEY -]; -/** -* Top-level params members carrying multi-round-trip driver material -* (protocol revision 2026-07-28). The spec reserves these names on -* client-initiated REQUESTS only — notification params keep them untouched -* (a vendor notification may legitimately use the same names). -*/ -const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; -/** -* Lift wire-only material out of an inbound message so handlers see exactly -* the 2025-era shape, and surface it for the protocol layer (requests: via -* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the -* reserved envelope `_meta` keys are reserved on every message, while the -* multi-round-trip retry fields (`inputResponses`/`requestState`) are -* reserved on client-initiated requests only — so notifications get only the -* envelope lift, and their top-level params stay untouched. Messages without -* wire-only material are returned unchanged (same reference). -*/ -function liftWireOnlyMaterial(message, kind) { - const params = message.params; - if (!isPlainObject$1(params)) return { - message, - lifted: {} - }; - const meta = params._meta; - const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; - const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; - if (envelopeKeys.length === 0 && retryKeys.length === 0) return { - message, - lifted: {} - }; - const lifted = {}; - const nextParams = { ...params }; - if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { - const envelope = {}; - const nextMeta = { ...meta }; - for (const key of envelopeKeys) { - envelope[key] = meta[key]; - delete nextMeta[key]; - } - lifted.envelope = envelope; - if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; - else delete nextParams._meta; - } - for (const key of retryKeys) { - if (key === "inputResponses") lifted.inputResponses = nextParams[key]; - if (key === "requestState") lifted.requestState = nextParams[key]; - delete nextParams[key]; - } - return { - message: { - ...message, - params: nextParams - }, - lifted - }; -} -/** -* Standard Schema adapter over the era codec's `validateResult` function (the -* function-only WireCodec contract exposes no schema objects). Used by the -* spec-method `request()` overload so the request funnel keeps a single -* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema -* paths. -* -* Returns `undefined` when the method has no result entry on this era's -* registry — the caller maps that to the synchronous "pass a result schema" -* TypeError, exactly matching the pre-function-only behavior the -* typedMapAlignment suite pins (the result map deliberately excludes the -* `tasks/*` methods, so the spec-method overload refuses them up front). -*/ -function codecResultValidator(codec, method) { - const probe = codec.validateResult(method, void 0); - if (!probe.ok && probe.reason === "not-in-era") return void 0; - return { "~standard": { - version: 1, - vendor: "mcp-wire-codec", - validate(value) { - const outcome = codec.validateResult(method, value); - if (outcome.ok) return { value: outcome.value }; - return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; - } - } }; -} -/** -* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The -* `as T` below is the one place {@linkcode RequestStateAccessor}'s -* caller-asserted typing is implemented — no implementation can produce an -* arbitrary `T` from a runtime value honestly. -*/ -function requestStateAccessor(value) { - return () => value; -} -/** Shared no-state accessor: the common case allocates nothing per request. */ -const NO_REQUEST_STATE = requestStateAccessor(void 0); -/** -* Returns a context whose `requestState` accessor reads the given value — -* how the server seam hands a verify hook's decoded payload (or the legacy -* shim's per-round echo) to the handler without mutating the original -* context. -*/ -function withRequestStateValue(ctx, value) { - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - requestState: requestStateAccessor(value) - } - }; -} -let writeNegotiatedProtocolVersion; -/** -* Package-internal write channel for a {@linkcode Protocol} instance's -* negotiated protocol version, for callers outside the class hierarchy: -* tests and the (future) modern-era server entry that marks a factory -* instance modern at binding time. Exported on the core internal barrel -* only — never public API. -*/ -function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { - writeNegotiatedProtocolVersion(instance, version); -} -/** -* Implements MCP protocol framing on top of a pluggable transport, including -* features like request/response linking, notifications, and progress. -* -* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific -* implementations most code should use. -*/ -var Protocol = class { - _transport; - _requestMessageId = 0; - _requestHandlers = /* @__PURE__ */ new Map(); - _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - _notificationHandlers = /* @__PURE__ */ new Map(); - _responseHandlers = /* @__PURE__ */ new Map(); - _progressHandlers = /* @__PURE__ */ new Map(); - _timeoutInfo = /* @__PURE__ */ new Map(); - _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); - /** - * The protocol version negotiated for the current connection (`undefined` - * before negotiation completes), which determines the wire era this - * instance speaks. Set by the SDK's negotiation and initialize paths - * (`Client.connect`, `Server._oninitialize`). - */ - _negotiatedProtocolVersion; - static { - writeNegotiatedProtocolVersion = (instance, version) => { - instance._negotiatedProtocolVersion = version; - }; - } - _supportedProtocolVersions; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when {@linkcode Protocol.close | close()} is called as well. - */ - onclose; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler; - constructor(_options) { - this._options = _options; - this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; - this.setNotificationHandler("notifications/cancelled", (notification) => { - this._oncancel(notification); - }); - this.setNotificationHandler("notifications/progress", (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler("ping", (_request) => ({})); - } - /** - * Drop consult for inbound messages whose transport did not classify them - * at the edge — long-lived channels such as stdio, where a role class may - * need to decline traffic the negotiated era has no answer for (the - * client-side inbound-request drop on modern-era connections: the - * 2026-07-28 era has no server→client request channel, and on stdio the - * client must never write JSON-RPC responses). - * - * Consulted ONLY when the transport supplied no - * {@linkcode MessageExtraInfo.classification}: edge-classified traffic - * never reaches the hook. Returning `'drop'` discards the message without - * writing any response (requests are surfaced via `onerror`). The base - * implementation returns `undefined`: unclassified traffic keeps today's - * dispatch path unchanged. Era selection never happens here — era is - * instance state, owned by the serving entry that constructed and - * connected the instance. - */ - _shouldDropInbound(_message) {} - /** - * The per-request `_meta` envelope this instance attaches to every outgoing - * request and notification, when one applies. The base implementation - * returns `undefined` (no envelope — the 2025-era posture, so legacy-era - * outbound traffic is byte-identical to a build without this seam). - * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) - * era to return the reserved protocol-version / client-info / - * client-capabilities keys. User-supplied `_meta` keys take precedence over - * the auto-attached ones. - */ - _outboundMetaEnvelope() {} - /** - * Attach this instance's outbound `_meta` envelope (when one is configured) - * to a request or notification. A no-op when the seam returns `undefined` - * — the message returns by reference, so the legacy-era wire stays - * byte-identical. User-supplied `_meta` keys are spread last so they win - * over the auto-attached envelope keys. - */ - _envelopeOutbound(message) { - const envelope = this._outboundMetaEnvelope(); - if (envelope === void 0) return message; - const params = message.params ?? {}; - return { - ...message, - params: { - ...params, - _meta: { - ...envelope, - ...params._meta - } - } - }; - } - /** - * Extension point for non-`complete` decoded results in the response - * funnel: a result the wire codec discriminated into a kind other than - * `'complete'` or `'invalid'` is handed here for the role class to - * resolve. The base default surfaces it as a typed - * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). - * - * Intended consumers (named so the seam stays accountable): - * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils - * `'input_required'` results through the registered - * elicitation/sampling/roots handlers and retries via `flow.retry`; - * - a future client-side terminal-result handler for - * `subscriptions/listen`, when the spec defines one. - * - * `Server` instances never receive `input_required` responses on their - * outbound legs and leave the base behavior in place. - */ - _resolveNonCompleteResult(decoded, flow) { - return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { - resultType: decoded.kind, - method: flow.request.method - })); - } - /** - * Protected accessor for a registered request handler. Used by role - * classes that dispatch synthesized requests through the same stored - * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip - * input request). - */ - _getRequestHandler(method) { - return this._requestHandlers.get(method); - } - async _oncancel(notification) { - if (!notification.params.requestId) return; - this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - */ - async connect(transport) { - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - try { - _onclose?.(); - } finally { - this._onclose(); - } - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); - else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); - else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); - else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); - }; - transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); - await this._transport.start(); - } - /** - * Transport-close hook. Subclass overrides MUST call `super._onclose()` - * after their own cleanup — base teardown (response-handler settlement, - * timeout clearing, in-flight request abort) does not run otherwise. - */ - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); - this._timeoutInfo.clear(); - const requestHandlerAbortControllers = this._requestHandlerAbortControllers; - this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - try { - this.onclose?.(); - } finally { - for (const handler of responseHandlers.values()) handler(error); - for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - /** - * Inbound-notification dispatch. Subclass overrides MUST delegate - * unmatched traffic to `super._onnotification(rawNotification, extra)` — - * an override that consumes only what it owns and falls through to base - * dispatch for everything else. - */ - _onnotification(rawNotification, extra) { - const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); - return; - } - } - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; - const handler = this._notificationHandlers.get(notification.method); - const fallback = this.fallbackNotificationHandler; - if (handler === void 0 && fallback === void 0) return; - Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(rawRequest, extra) { - const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { - this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); - return; - } - const capturedTransport = this._transport; - const sendErrorResponse = (code, message, data) => { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }; - capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); - }; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); - const requested = extra.classification.revision ?? classified; - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { - supported: this._supportedProtocolVersions, - requested - }); - return; - } - } - if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - if (handler === void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const envelopeError = codec.checkInboundEnvelope(lifted); - if (envelopeError !== void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); - return; - } - const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { - ...options, - relatedRequestId: request.id - }); - const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { - ...options, - relatedRequestId: request.id - }); - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); - const baseCtx = { - sessionId: capturedTransport?.sessionId, - mcpReq: { - id: request.id, - method: request.method, - _meta: request.params?._meta, - ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, - ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, - ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, - requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), - signal: abortController.signal, - send: ((r, schemaOrOptions, maybeOptions) => { - const sendCodec = this._resolveOutboundCodec(r.method); - this._assertOutboundRequestInEra(sendCodec, r.method); - if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(sendCodec, r.method); - if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); - return sendRequest(r, validate, schemaOrOptions); - }), - notify: sendNotification - }, - http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 - }; - const ctx = this.buildContext(baseCtx, extra); - Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { - if (abortController.signal.aborted) return; - let encoded; - try { - encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); - } catch (error) { - this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); - return; - } - const response = { - result: encoded, - jsonrpc: "2.0", - id: request.id - }; - await capturedTransport?.send(response); - }, async (error) => { - if (abortController.signal.aborted) return; - const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: codec.encodeErrorCode(thrownCode), - message: error.message ?? "Internal error", - ...error["data"] !== void 0 && { data: error["data"] } - } - }; - await capturedTransport?.send(errorResponse); - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { - if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { - this._resetTimeout(messageId); - } catch (error) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - handler(params); - } - /** - * Inbound-response dispatch. Subclass overrides MUST delegate unmatched - * traffic to `super._onresponse(response)` — an override that consumes - * only what it owns and falls through to base dispatch for everything - * else. - */ - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === void 0) { - this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._progressHandlers.delete(messageId); - if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); - else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); - } - request(request, schemaOrOptions, maybeOptions) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(codec, request.method); - if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); - return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); - } - /** - * The wire codec for this instance's negotiated era — the phase-2 truth: - * everything an established connection sends and receives resolves - * through it. Legacy until a version has been negotiated. - */ - _negotiatedWireCodec() { - return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - } - /** - * Protected accessor for the instance's negotiated wire codec, for role - * classes (Client/Server/McpServer) routing era-dependent behavior - * through the codec's function-only surface — `samplingResultVariant`, - * `outboundEnvelope`, `projectCallToolResult` — instead of branching on - * the protocol version themselves. - */ - _wireCodec() { - return this._negotiatedWireCodec(); - } - /** - * Outbound codec resolution: while the negotiated version is still unset - * (the negotiation window), lifecycle messages are bootstrap-pinned BY - * METHOD — they self-identify their era (`initialize` IS the legacy - * handshake, `server/discover` IS the modern probe). Once a version has - * been negotiated, the instance era is authoritative for everything — a - * negotiated session never re-routes a method onto the other era. - */ - _resolveOutboundCodec(method) { - if (this._negotiatedProtocolVersion === void 0) { - const pinned = bootstrapOutboundCodec(method); - if (pinned) return pinned; - } - return this._negotiatedWireCodec(); - } - /** - * Era gate for outbound requests — deletions are physical in BOTH - * directions: sending a spec method that the resolved era does not define - * dies locally with a typed error before anything reaches the transport. - * Methods outside the spec universe are consumer-owned extension methods - * and stay era-blind. - */ - _assertOutboundRequestInEra(codec, method) { - if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method, - era: codec.era - }); - } - /** - * Sends a request and waits for a response, using the provided schema for - * validation instead of the era registry's method-keyed entry. - * - * This is the internal implementation used by SDK methods whose result - * schema cannot be expressed as a method-keyed registry entry — the one - * surviving case is `server.createMessage`, whose result schema depends - * on the REQUEST params (tools vs no tools) — and by callers passing - * explicit compatibility schemas. Spec methods are still era-gated here: - * an explicit schema never smuggles a deleted method onto the wire. - */ - _requestWithSchema(request, resultSchema, options) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); - } - /** - * The request funnel proper, keyed by the resolved era codec: the codec - * owns result decoding (raw-first `resultType` discrimination — V-1 — - * and the era's lift posture) before the schema validation step. - */ - _requestWithSchemaViaCodec(codec, request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; - const flowStartedAt = Date.now(); - let onAbort; - let cleanupMessageId; - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(/* @__PURE__ */ new Error("Not connected")); - return; - } - if (this._options?.enforceStrictCapabilities === true) try { - this.assertCapabilityForMethod(request.method); - } catch (error) { - earlyReject(error); - return; - } - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; - const messageId = this._requestMessageId++; - cleanupMessageId = messageId; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...request.params?._meta, - progressToken: messageId - } - }; - } - const outbound = this._envelopeOutbound(jsonrpcRequest); - let responseReceived = false; - const cancel = (reason) => { - if (responseReceived) return; - this._progressHandlers.delete(messageId); - if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }), { - relatedRequestId, - resumptionToken, - onresumptiontoken - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); - else requestAbort.abort(); - reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); - }; - this._responseHandlers.set(messageId, (response) => { - if (options?.signal?.aborted) return; - responseReceived = true; - if (response instanceof Error) return reject(response); - let decoded; - try { - decoded = codec.decodeResult(request.method, response.result); - } catch (error) { - return reject(error instanceof Error ? error : new Error(String(error))); - } - if (decoded.kind === "invalid") return reject(decoded.error); - if (decoded.kind === "input_required") { - if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); - const flow = { - codec, - request, - resultSchema, - options, - flowStartedAt, - retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { - method: request.method, - params - }, resultSchema, legOptions) - }; - return resolve(this._resolveNonCompleteResult(decoded, flow)); - } - const result = decoded.result; - validateStandardSchema(resultSchema, result).then((parseResult) => { - if (parseResult.success) resolve(parseResult.data); - else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); - }, reject); - }); - onAbort = () => cancel(options?.signal?.reason); - options?.signal?.addEventListener("abort", onAbort, { once: true }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - this._transport.send(outbound, { - relatedRequestId, - resumptionToken, - onresumptiontoken, - headers, - requestSignal: requestAbort?.signal - }).catch((error) => { - this._progressHandlers.delete(messageId); - reject(error); - }); - }).finally(() => { - if (onAbort) options?.signal?.removeEventListener("abort", onAbort); - if (cleanupMessageId !== void 0) { - this._responseHandlers.delete(cleanupMessageId); - this._cleanupTimeout(cleanupMessageId); - } - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); - } - /** - * The notification funnel proper, keyed by the resolved era codec — - * direct sends and related notifications (`ctx.mcpReq.notify`) alike - * resolve through the instance's negotiated era at send time. - */ - async _notificationViaCodec(codec, notification, options) { - if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method: notification.method, - era: codec.era - }); - this.assertNotificationCapability(notification.method); - const jsonrpcNotification = this._envelopeOutbound({ - jsonrpc: "2.0", - ...notification - }); - if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { - if (this._pendingDebouncedNotifications.has(notification.method)) return; - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) return; - this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); - }); - return; - } - await this._transport.send(jsonrpcNotification, options); - } - setRequestHandler(method, schemasOrHandler, maybeHandler) { - this.assertRequestHandlerCapability(method); - let stored; - if (typeof schemasOrHandler === "function") { - if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); - stored = (request, ctx) => { - const dispatchCodec = this._negotiatedWireCodec(); - let outcome = dispatchCodec.validateRequest(method, request); - if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value, ctx)); - }; - } else if (maybeHandler) stored = async (request, ctx) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); - return maybeHandler(parsed.data, ctx); - }; - else throw new TypeError("setRequestHandler: handler is required"); - this._requestHandlers.set(method, this._wrapHandler(method, stored)); - } - /** - * Hook for subclasses to wrap a registered request handler with role-specific - * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` - * validates `elicitation/create` mode and result). Runs for both the 2-arg and - * 3-arg registration paths. The default implementation is identity. - * - * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. - */ - _wrapHandler(_method, handler) { - return handler; - } - /** - * Hook for subclasses to supply the implementation identity the 2026-era - * encode seam stamps into outbound result `_meta` under - * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD - * identify themselves on every response). The default is `undefined` — no - * stamp. Only `Server` overrides this: the key identifies the software - * producing a response, and the 2025-era codec never stamps anything - * regardless (the never-stamp guarantee). - */ - _outboundServerInfo() {} - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - setNotificationHandler(method, schemasOrHandler, maybeHandler) { - if (typeof schemasOrHandler === "function") { - if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); - this._notificationHandlers.set(method, (notification, codec) => { - const outcome = codec.validateNotification(method, notification); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value)); - }); - return; - } - if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); - this._notificationHandlers.set(method, async (notification) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); - await maybeHandler(parsed.data, notification); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -}; -function isPlainObject$1(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === void 0) continue; - const baseValue = result[k]; - result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { - ...baseValue, - ...addValue - } : addValue; - } - return result; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredEngine.ts -function src_CX2iR2pK_isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -/** -* Splits a retried request's `inputResponses` map into the BARE response -* entries the spec defines and everything else. The spec's embedded responses -* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or -* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some -* peers emit) is never accepted as a response — its key is recorded so the -* handler can re-issue the corresponding input request. -*/ -function partitionInputResponses(inputResponses) { - const accepted = {}; - const droppedKeys = []; - if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { - accepted, - droppedKeys - }; - for (const [key, entry] of Object.entries(inputResponses)) { - if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { - droppedKeys.push(key); - continue; - } - accepted[key] = entry; - } - return { - accepted, - droppedKeys - }; -} -/** -* Builds the manual-mode {@linkcode InputRequiredResult} value from the -* codec's decoded payload — what an `allowInputRequired: true` caller -* receives instead of the auto-fulfilled complete result. -*/ -function manualInputRequiredValue(decoded) { - return { - resultType: "input_required", - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; -} - -//#endregion -//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js -/*! -* content-type -* Copyright(c) 2015 Douglas Christopher Wilson -* MIT Licensed -*/ -var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { - /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.parse = parse; - /** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - function parse(string) { - if (!string) throw new TypeError("argument string is required"); - var header = typeof string === "object" ? getcontenttype(string) : string; - if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); - var index = header.indexOf(";"); - var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); - var obj = new ContentType(type.toLowerCase()); - if (index !== -1) { - var key; - var match; - var value; - PARAM_REGEXP.lastIndex = index; - while (match = PARAM_REGEXP.exec(header)) { - if (match.index !== index) throw new TypeError("invalid parameter format"); - index += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value.charCodeAt(0) === 34) { - value = value.slice(1, -1); - if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); - } - obj.parameters[key] = value; - } - if (index !== header.length) throw new TypeError("invalid parameter format"); - } - return obj; - } - /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - function getcontenttype(obj) { - var header; - if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); - else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; - if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); - return header; - } - /** - * Class to represent a content type. - * @private - */ - function ContentType(type) { - this.parameters = Object.create(null); - this.type = type; - } -})); - -//#endregion -//#region ../core-internal/src/shared/mediaType.ts -var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); -/** -* Extracts the media type (the lowercased `type/subtype` pair, without -* parameters) from a raw `Content-Type` header value, or `undefined` when the -* header is missing or empty. -* -* Content-Type comparisons must use the parsed media type, never a substring -* search of the raw header: a value like `text/plain; a=application/json` -* contains the substring `application/json` but its media type is -* `text/plain`, and case variants or parameters make naive string comparison -* wrong in both directions. -* -* "Essence" is the WHATWG MIME Sniffing standard's term for the bare -* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); -* the Fetch standard's request classification is defined against it -* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). -* -* Parsing is RFC 9110 (`content-type` package) first. When the parameter -* section is malformed (`application/json;`, `application/json; charset=`), -* browsers and most HTTP stacks still derive the media type from the segment -* before the first `;` — the fallback matches that widely-implemented -* behavior, so a header whose media type is unambiguous is not rejected for -* a sloppy parameter section. -*/ -function src_CX2iR2pK_mediaTypeEssence(header) { - if (!header) return; - try { - return import_content_type.parse(header).type; - } catch { - const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); - if (essence === "" || header.slice(essence.length).includes(",")) return; - return essence; - } -} -/** -* Whether a raw `Content-Type` header value denotes `application/json`. -* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed -* parameter sections do not reject a header whose media type is unambiguously -* `application/json` (see `mediaTypeEssence` for the exact grammar). -*/ -function src_CX2iR2pK_isJsonContentType(header) { - if (header === "application/json") return true; - return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; -} - -//#endregion -//#region ../core-internal/src/shared/metadataUtils.ts -/** -* Utilities for working with {@linkcode BaseMetadata} objects. -*/ -/** -* Gets the display name for an object with {@linkcode BaseMetadata}. -* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` -* For other objects: `title` → `name` -* This implements the spec requirement: "if no title is provided, name should be used for display purposes" -*/ -function getDisplayName(metadata) { - if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; - if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; - return metadata.name; -} - -//#endregion -//#region ../core-internal/src/shared/stdio.ts -const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; -/** -* Buffers a continuous stdio stream into discrete JSON-RPC messages. -*/ -var ReadBuffer = class { - _buffer; - _maxBufferSize; - constructor(options) { - this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; - } - append(chunk) { - if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { - this.clear(); - throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); - } - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - while (this._buffer) { - const index = this._buffer.indexOf("\n"); - if (index === -1) return null; - const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); - this._buffer = this._buffer.subarray(index + 1); - try { - return deserializeMessage(line); - } catch (error) { - if (error instanceof SyntaxError) continue; - throw error; - } - } - return null; - } - clear() { - this._buffer = void 0; - } -}; -function deserializeMessage(line) { - return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + "\n"; -} - -//#endregion -//#region ../core-internal/src/shared/toolNameValidation.ts -/** -* Tool name validation utilities according to SEP: Specify Format for Tool Names -* -* Tool names SHOULD be between 1 and 128 characters in length (inclusive). -* Tool names are case-sensitive. -* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits -* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). -* Tool names SHOULD NOT contain spaces, commas, or other special characters. -* -* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} -*/ -/** -* Regular expression for valid tool names according to SEP-986 specification -*/ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** -* Validates a tool name according to the SEP specification -* @param name - The tool name to validate -* @returns An object containing validation result and any warnings -*/ -function validateToolName(name) { - const warnings = []; - if (name.length === 0) return { - isValid: false, - warnings: ["Tool name cannot be empty"] - }; - if (name.length > 128) return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); - if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); - if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); - if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** -* Issues warnings for non-conforming tool names -* @param name - The tool name that triggered the warnings -* @param warnings - Array of warning messages -*/ -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) console.warn(` - ${warning}`); - console.warn("Tool registration will proceed, but this may cause compatibility issues."); - console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); - console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); - } -} -/** -* Validates a tool name and issues warnings for non-conforming names -* @param name - The tool name to validate -* @returns `true` if the name is valid, `false` otherwise -*/ -function validateAndWarnToolName(name) { - const result = validateToolName(name); - issueToolNameWarning(name, result.warnings); - return result.isValid; -} - -//#endregion -//#region ../core-internal/src/shared/transport.ts -/** -* Normalizes `HeadersInit` to a plain `Record` for manipulation. -* Handles `Headers` objects, arrays of tuples, and plain objects. -*/ -function normalizeHeaders(headers) { - if (!headers) return {}; - if (headers instanceof Headers) return Object.fromEntries(headers.entries()); - if (Array.isArray(headers)) return Object.fromEntries(headers); - return { ...headers }; -} -/** -* Creates a fetch function that includes base `RequestInit` options. -* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. -* -* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) -* @param baseInit - The base `RequestInit` to merge with each request -* @returns A wrapped fetch function that merges base options with call-specific options -*/ -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) return baseFetch; - return async (url, init) => { - return baseFetch(url, { - ...baseInit, - ...init, - headers: init?.headers ? { - ...normalizeHeaders(baseInit.headers), - ...normalizeHeaders(init.headers) - } : baseInit.headers - }); - }; -} - -//#endregion -//#region ../core-internal/src/shared/uriTemplate.ts -const MAX_TEMPLATE_LENGTH = 1e6; -const MAX_VARIABLE_LENGTH = 1e6; -const MAX_TEMPLATE_EXPRESSIONS = 1e4; -const MAX_REGEX_LENGTH = 1e6; -var src_CX2iR2pK_UriTemplate = class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like `{foo}` or `{?bar}`. - */ - static isTemplate(str) { - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - template; - parts; - get variableNames() { - return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ""; - let i = 0; - let expressionCount = 0; - while (i < template.length) if (template[i] === "{") { - if (currentText) { - parts.push(currentText); - currentText = ""; - } - const end = template.indexOf("}", i); - if (end === -1) throw new Error("Unclosed template expression"); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes("*"); - const names = this.getNames(expr); - const name = names[0]; - for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - parts.push({ - name, - operator, - names, - exploded - }); - i = end + 1; - } else { - currentText += template[i]; - i++; - } - if (currentText) parts.push(currentText); - return parts; - } - getOperator(expr) { - return [ - "+", - "#", - ".", - "/", - "?", - "&" - ].find((op) => expr.startsWith(op)) || ""; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); - if (operator === "+" || operator === "#") return encodeURI(value); - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === "?" || part.operator === "&") { - const pairs = part.names.map((name) => { - const value$1 = variables[name]; - if (value$1 === void 0) return ""; - return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; - }).filter((pair) => pair.length > 0); - if (pairs.length === 0) return ""; - return (part.operator === "?" ? "?" : "&") + pairs.join("&"); - } - if (part.names.length > 1) { - const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); - if (values.length === 0) return ""; - return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); - } - const value = variables[part.name]; - if (value === void 0) return ""; - const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); - switch (part.operator) { - case "": return encoded.join(","); - case "+": return encoded.join(","); - case "#": return "#" + encoded.join(","); - case ".": return "." + encoded.join("."); - case "/": return "/" + encoded.join("/"); - default: return encoded.join(","); - } - } - expand(variables) { - let result = ""; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === "string") { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) continue; - result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; - if (part.operator === "?" || part.operator === "&") hasQueryParam = true; - } - return result; - } - escapeRegExp(str) { - return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); - } - partToRegExp(part) { - const patterns = []; - for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - if (part.operator === "?" || part.operator === "&") { - for (let i = 0; i < part.names.length; i++) { - const name$1 = part.names[i]; - const prefix = i === 0 ? "\\" + part.operator : "&"; - patterns.push({ - pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", - name: name$1 - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case "": - pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; - break; - case "+": - case "#": - pattern = "(.+)"; - break; - case ".": - pattern = String.raw`\.([^/,]+)`; - break; - case "/": - pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); - break; - default: pattern = "([^/]+)"; - } - patterns.push({ - pattern, - name - }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); - let pattern = "^"; - const names = []; - for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ - name, - exploded: part.exploded - }); - } - } - pattern += "$"; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) return null; - const result = {}; - for (const [i, name_] of names.entries()) { - const { name, exploded } = name_; - const value = match[i + 1]; - const cleanName = name.replace("*", ""); - result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; - } - return result; - } -}; - -//#endregion -//#region ../core-internal/src/util/inMemory.ts -/** -* In-memory transport for creating clients and servers that talk to each other within the same process. -* -* Intended for testing and development. For production in-process connections, use -* `StreamableHTTPClientTransport` against a local server URL. -*/ -var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { - _otherTransport; - _messageQueue = []; - _closed = false; - onclose; - onerror; - onmessage; - sessionId; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - this.onmessage?.(queuedMessage.message, queuedMessage.extra); - } - } - async close() { - if (this._closed) return; - this._closed = true; - const other = this._otherTransport; - this._otherTransport = void 0; - try { - await other?.close(); - } finally { - this.onclose?.(); - } - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); - else this._otherTransport._messageQueue.push({ - message, - extra: { authInfo: options?.authInfo } - }); - } -}; - -//#endregion -//#region ../core-internal/src/util/zodCompat.ts -/** -* Zod-specific helpers for the v1-compat raw-shape shorthand on -* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so -* that file stays library-agnostic per the Standard Schema spec. -*/ -function isZodV4Schema(v) { - return typeof v === "object" && v !== null && "_zod" in v; -} -function looksLikeZodV3(v) { - return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; -} -/** -* Detects a "raw shape" — a plain object whose values are Zod field schemas, -* e.g. `{ name: z.string() }`. Powers the auto-wrap in -* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only -* Zod values are supported. -* -* @internal -*/ -function isZodRawShape(obj) { - if (typeof obj !== "object" || obj === null) return false; - if (isStandardSchema(obj)) return false; - const proto = Object.getPrototypeOf(obj); - if (proto !== Object.prototype && proto !== null) return false; - return Object.values(obj).every((v) => isZodV4Schema(v)); -} -/** -* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape -* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. -* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a -* uniform schema type; already-wrapped schemas pass through unchanged. -* -* @internal -*/ -function normalizeRawShapeSchema(schema) { - if (schema === void 0) return void 0; - if (isZodRawShape(schema)) return schemas_object(schema); - if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); - if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); - return schema; -} - -//#endregion -//#region ../core-internal/src/wire/preload.ts -/** -* Explicit warm-up entry for the lazy wire-schema layers. -* -* The per-revision wire schemas are built lazily: each era's schema set sits -* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the -* registry/codec lookup maps above those factories are memoized the same way. -* That laziness is the right default on process-per-invocation runtimes (CLI -* tools, dev servers), where module evaluation IS startup latency and most -* short-lived processes never validate a message on both eras. -* -* On platforms that bill request CPU but not module evaluation — isolate-based -* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: -* module-scope work runs during isolate warm-up outside any request, while -* lazy construction lands inside the first request's billed (and latency -* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move -* the one-time construction cost back to module scope by calling it at module -* scope themselves. The packages' own workerd shims already do this, so -* Workers deployments get eager construction automatically. -*/ -/** -* Eagerly builds every lazily-constructed wire-schema layer, so that no later -* validation pays schema-construction cost. -* -* Synchronous and idempotent: every layer is a memo, so the first call does -* all the work and subsequent calls return immediately. Reference identity is -* unaffected — this forces the same memos every lazy consumer pulls through. -* -* Call it at module scope on platforms that bill per-request CPU but not -* module evaluation (isolate-based edge/serverless runtimes), where deferring -* construction would move it into the first request of every fresh isolate: -* -* ```ts -* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — -* // each package bundles its own schema copy, so warm the one(s) you import. -* preloadSchemas(); // module scope — runs during isolate warm-up -* ``` -* -* On Node CLIs and other process-per-invocation runtimes, prefer the lazy -* default — there, module-scope construction is pure added boot latency. -*/ -function preloadSchemas() { - buildSchemas2025(); - buildSchemas2026(); - warmRegistryMaps2025(); - warmInputSchemaMaps2026(); - warmWireResultSchemas2026(); -} - -//#endregion -//#region ../core-internal/src/validators/fromJsonSchema.ts -/** -* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be -* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON -* Schema (e.g. from TypeBox, or hand-written) and want to register it without going -* through a Standard Schema library. -* -* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript -* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. -* -* @param schema - A JSON Schema object describing the expected shape -* @param validator - A validator provider. When importing `fromJsonSchema` from -* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate -* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). -* -* @example -* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" -* const inputSchema = fromJsonSchema<{ name: string }>( -* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, -* validator -* ); -* // Use with server.registerTool('greet', { inputSchema }, handler) -* ``` -*/ -function fromJsonSchema(schema, validator) { - const check = validator.getValidator(schema); - return { "~standard": { - version: 1, - vendor: "mcp", - jsonSchema: { - input: () => schema, - output: () => schema - }, - validate: (data) => { - const result = check(data); - return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; - } - } }; -} - -//#endregion - -//# sourceMappingURL=src-CX2iR2pK.mjs.map - - - -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class {}; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name = class extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) return false; - const item = this._items[0]; - return item === "" || item === "\"\""; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - const plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) code.push(...arg._items); - else if (arg instanceof Name) code.push(arg); - else code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === "\"\"") return a; - if (a === "\"\"") return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== "\"") return; - if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; - if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - const code_1 = require_code$1(); - var ValueError = class extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - }; - var UsedValueState; - (function(UsedValueState) { - UsedValueState[UsedValueState["Started"] = 0] = "Started"; - UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - return this._names[prefix] = { - prefix, - index: 0 - }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - const line = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { - ...opts, - _n: opts.lines ? line : code_1.nil - }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) return _name; - } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { - property: prefix, - itemIndex - }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; - else throw new ValueError(name); - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - }; - exports.ValueScope = ValueScope; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - const code_1 = require_code$1(); - const scope_1 = require_scope(); - var code_2 = require_code$1(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return code_2._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return code_2.str; - } - }); - Object.defineProperty(exports, "strConcat", { - enumerable: true, - get: function() { - return code_2.strConcat; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return code_2.nil; - } - }); - Object.defineProperty(exports, "getProperty", { - enumerable: true, - get: function() { - return code_2.getProperty; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return code_2.stringify; - } - }); - Object.defineProperty(exports, "regexpCode", { - enumerable: true, - get: function() { - return code_2.regexpCode; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return code_2.Name; - } - }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function() { - return scope_2.Scope; - } - }); - Object.defineProperty(exports, "ValueScope", { - enumerable: true, - get: function() { - return scope_2.ValueScope; - } - }); - Object.defineProperty(exports, "ValueScopeName", { - enumerable: true, - get: function() { - return scope_2.ValueScopeName; - } - }); - Object.defineProperty(exports, "varKinds", { - enumerable: true, - get: function() { - return scope_2.varKinds; - } - }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) return; - if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - }; - var Assign = class extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); - } - }; - var AssignOp = class extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - }; - var Label = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - }; - var Break = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `break${this.label ? ` ${this.label}` : ""};` + _n; - } - }; - var Throw = class extends Node { - constructor(error) { - super(); - this.error = error; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - }; - var AnyCode = class extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - }; - var ParentNode = class extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) nodes.splice(i, 1, ...n); - else if (n) nodes[i] = n; - else nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - }; - var BlockNode = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode {}; - var Else = class extends BlockNode {}; - Else.kind = "else"; - var If = class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) return e instanceof If ? e : e.nodes; - if (this.nodes.length) return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) return void 0; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) addNames(names, this.else.names); - return names; - } - }; - If.kind = "if"; - var For = class extends BlockNode {}; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - }; - var ForRange = class extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - return addExprNames(addExprNames(super.names, this.from), this.to); - } - }; - var ForIter = class extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - }; - var Func = class extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); - } - }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - }; - Return.kind = "return"; - var Try = class extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) code += this.catch.render(opts); - if (this.finally) code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) addNames(names, this.catch.names); - if (this.finally) addNames(names, this.finally.names); - return names; - } - }; - var Catch = class extends BlockNode { - constructor(error) { - super(); - this.error = error; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { - ...opts, - _n: opts.lines ? "\n" : "" - }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") c(); - else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); - else if (thenBody) this.code(thenBody).endIf(); - else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error = this.name("e"); - this._currNode = node.catch = new Catch(error); - catchCode(error); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error) { - return this._leafNode(new Throw(error)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) return replaceName(expr); - if (!canOptimize(expr)) return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) c = replaceName(c); - if (c instanceof code_1._Code) items.push(...c._items); - else items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - const andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - const orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - const codegen_1 = require_codegen(); - const code_1 = require_code$1(); - function toHash(arr) { - const hash = {}; - for (const item of arr) hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") return schema; - if (Object.keys(schema).length === 0) return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self } = it; - if (!opts.strictSchema) return; - if (typeof schema === "boolean") return; - const rules = self.RULES.keywords; - for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (rules[key]) return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") return schema; - if (typeof schema == "string") return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) for (const x of xs) f(x); - else f(xs); - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) gen.assign(to, true); - else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { - ...from, - ...to - }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - const snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type) { - Type[Type["Num"] = 0] = "Num"; - Type[Type["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) return; - msg = `strict mode: ${msg}`; - if (mode === true) throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; - exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); - else returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - exports.reportError = reportError; - function reportExtraError(cxt, error = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - addError(gen, errorObjectCode(cxt, error, errorPaths)); - if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - /* istanbul ignore if */ - if (errsCount === void 0) throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - const E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error, errorPaths); - } - function errorObject(cxt, error, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; - extraErrorProps(cxt, error, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - if (propertyName) keyValues.push([E.propertyName, propertyName]); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const boolError = { message: "boolean schema is false" }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) falseSchemaError(it, false); - else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else gen.var(valid, true); - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - const jsonTypes = new Set([ - "string", - "number", - "integer", - "boolean", - "null", - "object", - "array" - ]); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { - type: "number", - rules: [] - }, - string: { - type: "string", - rules: [] - }, - array: { - type: "array", - rules: [] - }, - object: { - type: "object", - rules: [] - } - }; - return { - types: { - ...groups, - integer: true, - boolean: true, - null: true - }, - rules: [ - { rules: [] }, - groups.number, - groups.string, - groups.array, - groups.object - ], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self }, type) { - const group = self.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - const rules_1 = require_rules(); - const applicability_1 = require_applicability(); - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - var DataType; - (function(DataType) { - DataType[DataType["Correct"] = 0] = "Correct"; - DataType[DataType["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - if (types.includes("null")) { - if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); - if (schema.nullable === true) types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) coerceData(it, types, coerceTo); - else reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - const COERCIBLE = new Set([ - "string", - "number", - "integer", - "boolean", - "null" - ]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else cond = codegen_1.nil; - if (types.number) delete types.integer; - for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - const typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); - else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - const newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const code_1 = require_code(); - const errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a$1; - gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { - ref: result, - code: (0, codegen_1.stringify)(result) - }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { - /* istanbul ignore if */ - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - if (def.validateSchema) { - if (!def.validateSchema(schema[keyword])) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") self.logger.error(msg); - else throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error("either \"keyword\" or \"schema\" must be passed"); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); - if (propertyName !== void 0) subschema.propertyName = propertyName; - } - if (dataTypes) subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) subschema.compositeRule = compositeRule; - if (createErrors !== void 0) subschema.createErrors = createErrors; - if (allErrors !== void 0) subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0;) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { - var traverse = module.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - const util_1 = require_util(); - const equal = require_fast_deep_equal(); - const traverse = require_json_schema_traverse(); - const SIMPLE_INLINED = new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") return true; - if (limit === true) return !hasRef(schema); - if (!limit) return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - const REF_KEYWORDS = new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) return true; - if (typeof sch == "object" && hasRef(sch)) return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) continue; - if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - if (count === Infinity) return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) id = normalizeId(id); - return _getFullPath(resolver, resolver.parse(id)); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - return resolver.serialize(p).split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - const TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); - else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else this.refs[ref] = fullPath; - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); - } - function ambiguos(ref) { - return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - const boolSchema_1 = require_boolSchema(); - const dataType_1 = require_dataType(); - const applicability_1 = require_applicability(); - const dataType_2 = require_dataType(); - const defaults_1 = require_defaults(); - const keyword_1 = require_keyword(); - const subschema_1 = require_subschema(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self }) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (self.RULES.all[key]) return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self } = it; - const { RULES } = self; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else iterateKeywords(it, group); - if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); - else if (withTypes.includes("integer") && t === "number") ts.push("integer"); - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) failAction(); - else this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) this.gen.endIf(); - } else if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - fail$data(condition) { - if (!this.$data) return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) Object.assign(this.params, obj); - else this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - /* istanbul ignore if */ - if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { - ...this.it, - ...subschema, - items: void 0, - props: void 0 - }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) return; - if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) def.code(cxt, ruleType); - else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); - else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - } - const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - }; - exports.default = ValidationError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - }; - exports.default = MissingRefError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - const codegen_1 = require_codegen(); - const validation_error_1 = require_validation_error(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { - es5, - lines, - ownProperties - }); - let _ValidationError; - if (sch.$async) _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { - ref: sch.schema, - code: (0, codegen_1.stringify)(sch.schema) - } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); - const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) validate.$async = true; - if (this.opts.code.source === true) validate.source = { - validateName, - validateCode, - scopeValues: gen._values - }; - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) return schOrFunc; - let _sch = resolve.call(this, root, ref); - if (_sch === void 0) { - const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) _sch = new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - if (_sch === void 0) return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; - if (!schOrRef.validate) compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - const PREVENT_SCOPE_CHANGE = new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - if (env.schema !== env.root.schema) return env; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", - "type": "object", - "required": ["$data"], - "properties": { "$data": { - "type": "string", - "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] - } }, - "additionalProperties": false - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { - /** @type {(value: string) => boolean} */ - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - /** @type {(value: string) => boolean} */ - const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); - /** - * @param {Array} input - * @returns {string} - */ - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (code === 48) continue; - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - break; - } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - } - return acc; - } - /** - * @typedef {Object} GetIPV6Result - * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. - * @property {string} address - The parsed IPv6 address. - * @property {string} [zone] - The zone identifier, if present. - */ - /** - * @param {string} value - * @returns {boolean} - */ - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - /** - * @param {Array} buffer - * @returns {boolean} - */ - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - /** - * @param {Array} buffer - * @param {Array} address - * @param {GetIPV6Result} output - * @returns {boolean} - */ - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== "") address.push(hex); - else { - output.error = true; - return false; - } - buffer.length = 0; - } - return true; - } - /** - * @param {string} input - * @returns {GetIPV6Result} - */ - function getIPV6(input) { - let tokenCount = 0; - const output = { - error: false, - address: "", - zone: "" - }; - /** @type {Array} */ - const address = []; - /** @type {Array} */ - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === "[" || cursor === "]") continue; - if (cursor === ":") { - if (endipv6Encountered === true) endIpv6 = true; - if (!consume(buffer, address, output)) break; - if (++tokenCount > 7) { - output.error = true; - break; - } - if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; - address.push(":"); - continue; - } else if (cursor === "%") { - if (!consume(buffer, address, output)) break; - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue; - } - } - if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); - else if (endIpv6) address.push(buffer.join("")); - else address.push(stringArrayToHexStripped(buffer)); - output.address = address.join(""); - return output; - } - /** - * @typedef {Object} NormalizeIPv6Result - * @property {string} host - The normalized host. - * @property {string} [escapedHost] - The escaped host. - * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. - */ - /** - * @param {string} host - * @returns {NormalizeIPv6Result} - */ - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) return { - host, - isIPV6: false - }; - const ipv6 = getIPV6(host); - if (!ipv6.error) { - let newHost = ipv6.address; - let escapedHost = ipv6.address; - if (ipv6.zone) { - newHost += "%" + ipv6.zone; - escapedHost += "%25" + ipv6.zone; - } - return { - host: newHost, - isIPV6: true, - escapedHost - }; - } else return { - host, - isIPV6: false - }; - } - /** - * @param {string} str - * @param {string} token - * @returns {number} - */ - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; - return ind; - } - /** - * @param {string} path - * @returns {string} - * - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 - */ - function removeDotSegments(path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) if (input === ".") break; - else if (input === "/") { - output.push("/"); - break; - } else { - output.push(input); - break; - } - else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") break; - else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) output.pop(); - output.push("/"); - break; - } - } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; - } - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) output.pop(); - continue; - } - } - } - } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join(""); - } - /** - * @param {import('../types/index').URIComponent} component - * @param {boolean} esc - * @returns {import('../types/index').URIComponent} - */ - function normalizeComponentEncoding(component, esc) { - const func = esc !== true ? escape : unescape; - if (component.scheme !== void 0) component.scheme = func(component.scheme); - if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); - if (component.host !== void 0) component.host = func(component.host); - if (component.path !== void 0) component.path = func(component.path); - if (component.query !== void 0) component.query = func(component.query); - if (component.fragment !== void 0) component.fragment = func(component.fragment); - return component; - } - /** - * @param {import('../types/index').URIComponent} component - * @returns {string|undefined} - */ - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; - else host = component.host; - } - uriTokens.push(host); - } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { isUUID } = require_utils(); - const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - const supportedSchemeNames = [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ]; - /** @typedef {supportedSchemeNames[number]} SchemeName */ - /** - * @param {string} name - * @returns {name is SchemeName} - */ - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf(name) !== -1; - } - /** - * @callback SchemeFn - * @param {import('../types/index').URIComponent} component - * @param {import('../types/index').Options} options - * @returns {import('../types/index').URIComponent} - */ - /** - * @typedef {Object} SchemeHandler - * @property {SchemeName} scheme - The scheme name. - * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. - * @property {SchemeFn} parse - Function to parse the URI component for this scheme. - * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. - * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. - * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. - * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. - */ - /** - * @param {import('../types/index').URIComponent} wsComponent - * @returns {boolean} - */ - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) return true; - else if (wsComponent.secure === false) return false; - else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - else return false; - } - /** @type {SchemeFn} */ - function httpParse(component) { - if (!component.host) component.error = component.error || "HTTP URIs must have a host."; - return component; - } - /** @type {SchemeFn} */ - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; - if (!component.path) component.path = "/"; - return component; - } - /** @type {SchemeFn} */ - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path && path !== "/" ? path : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); - urnComponent.path = void 0; - if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); - } else urnComponent.error = urnComponent.error || "URN can not be parsed."; - return urnComponent; - } - /** @type {SchemeFn} */ - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); - if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - /** @type {SchemeFn} */ - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; - return uuidComponent; - } - /** @type {SchemeFn} */ - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - const http = { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }; - const https = { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - }; - const ws = { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }; - const wss = { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }; - const urn = { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }; - const urnuuid = { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }; - const SCHEMES = { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - }; - Object.setPrototypeOf(SCHEMES, null); - /** - * @param {string|undefined} scheme - * @returns {SchemeHandler|undefined} - */ - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - const { SCHEMES, getSchemeHandler } = require_schemes(); - /** - * @template {import('./types/index').URIComponent|string} T - * @param {T} uri - * @param {import('./types/index').Options} [options] - * @returns {T} - */ - function normalize(uri, options) { - if (typeof uri === "string") uri = serialize(parse(uri, options), options); - else if (typeof uri === "object") uri = parse(serialize(uri, options), options); - return uri; - } - /** - * @param {string} baseURI - * @param {string} relativeURI - * @param {import('./types/index').Options} [options] - * @returns {string} - */ - function resolve(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - /** - * @param {import ('./types/index').URIComponent} base - * @param {import ('./types/index').URIComponent} relative - * @param {import('./types/index').Options} [options] - * @param {boolean} [skipNormalization=false] - * @returns {import ('./types/index').URIComponent} - */ - function resolveComponent(base, relative, options, skipNormalization) { - /** @type {import('./types/index').URIComponent} */ - const target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== void 0) target.query = relative.query; - else target.query = base.query; - } else { - if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); - else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; - else if (!base.path) target.path = relative.path; - else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; - } - /** - * @param {import ('./types/index').URIComponent|string} uriA - * @param {import ('./types/index').URIComponent|string} uriB - * @param {import ('./types/index').Options} options - * @returns {boolean} - */ - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { - ...options, - skipEscape: true - }); - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { - ...options, - skipEscape: true - }); - return uriA.toLowerCase() === uriB.toLowerCase(); - } - /** - * @param {Readonly} cmpts - * @param {import('./types/index').Options} [opts] - * @returns {string} - */ - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); - } else component.path = unescape(component.path); - if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") uriTokens.push("//"); - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") uriTokens.push("/"); - } - if (component.path !== void 0) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); - if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); - uriTokens.push(s); - } - if (component.query !== void 0) uriTokens.push("?", component.query); - if (component.fragment !== void 0) uriTokens.push("#", component.fragment); - return uriTokens.join(""); - } - const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - /** - * @param {string} uri - * @param {import('./types/index').Options} [opts] - * @returns - */ - function parse(uri, opts) { - const options = Object.assign({}, opts); - /** @type {import('./types/index').URIComponent} */ - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP = false; - if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; - else uri = "//" + uri; - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) parsed.port = matches[5]; - if (parsed.host) if (isIPv4(parsed.host) === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else isIP = true; - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; - else if (parsed.scheme === void 0) parsed.reference = "relative"; - else if (parsed.fragment === void 0) parsed.reference = "absolute"; - else parsed.reference = "uri"; - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); - if (parsed.host !== void 0) parsed.host = unescape(parsed.host); - } - if (parsed.path) parsed.path = escape(unescape(parsed.path)); - if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); - } else parsed.error = parsed.error || "URI can not be parsed."; - return parsed; - } - const fastUri = { - SCHEMES, - normalize, - resolve, - resolveComponent, - equal, - serialize, - parse - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const uri = require_fast_uri(); - uri.code = "require(\"ajv/dist/runtime/uri\").default"; - exports.default = uri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - const validation_error_1 = require_validation_error(); - const ref_error_1 = require_ref_error(); - const rules_1 = require_rules(); - const compile_1 = require_compile(); - const codegen_2 = require_codegen(); - const resolve_1 = require_resolve(); - const dataType_1 = require_dataType(); - const util_1 = require_util(); - const $dataRefSchema = require_data(); - const uri_1 = require_uri(); - const defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - const META_IGNORE_OPTIONS = [ - "removeAdditional", - "useDefaults", - "coerceTypes" - ]; - const EXT_SCOPE_NAMES = new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - const removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: "\"nullable\" keyword is supported by default.", - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: "\"uniqueItems\" keyword is always validated.", - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now." - }; - const deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." - }; - const MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { - ...o.code, - optimize, - regExp - } : { - optimize, - regExp - }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { - ...opts, - ...requiredOptions(opts) - }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ - scope: {}, - prefixes: EXT_SCOPE_NAMES, - es5, - lines - }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else v = this.compile(schemaKeyRef); - const valid = v(data); - if (!("$async" in v)) this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") this.logger.error(message); - else throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ - schema: {}, - schemaId - }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); - } else throw new Error("invalid addKeywords parameters"); - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) return "No errors"; - return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") delete schemas[keyRef]; - else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") id = schema[schemaId]; - else if (this.opts.jtd) throw new Error("schema must be object"); - else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); - let sch = this._cache.get(schema); - if (sch !== void 0) return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ - schema, - schemaId, - meta, - baseId, - localRefs - }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); - } - _compileSchemaEnv(sch) { - if (sch.meta) this._compileMetaSchema(sch); - else compile_1.compileSchema.call(this, sch); - /* istanbul ignore if */ - if (!sch.validate) throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); - else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; - return metaOpts; - } - const noLogs = { - log() {}, - warn() {}, - error() {} - }; - function getLogger(logger) { - if (logger === false) return noLogs; - if (logger === void 0) return console; - if (logger.log && logger.warn && logger.error) return logger; - throw new Error("logger must implement log, warn and error methods"); - } - const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) return; - if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { - type: dataType, - rules: [] - }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); - else ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) ruleGroup.rules.splice(i, 0, rule); - else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) return; - if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "id", - code() { - throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - const ref_error_1 = require_ref_error(); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const util_1 = require_util(); - const def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); - if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - callRef(cxt, getValidate(cxt, sch), sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { - ref: sch, - code: (0, codegen_1.stringify)(sch) - } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) callAsyncRef(); - else callSyncRef(); - function callAsyncRef() { - if (!env.$async) throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - exports.callRef = callRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const id_1 = require_id(); - const ref_1 = require_ref(); - const core = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - maximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - minimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - exclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - exclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const ucs2length_1 = require_ucs2length(); - const def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const util_1 = require_util(); - const codegen_1 = require_codegen(); - const def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) allErrorsMode(); - else exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - function allErrorsMode() { - if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); - else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const equal = require_fast_deep_equal(); - equal.code = "require(\"ajv/dist/runtime/equal\").default"; - exports.default = equal; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dataType_1 = require_dataType(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ - i, - j - }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "const", - $data: true, - error: { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const limitNumber_1 = require_limitNumber(); - const multipleOf_1 = require_multipleOf(); - const limitLength_1 = require_limitLength(); - const pattern_1 = require_pattern(); - const limitProperties_1 = require_limitProperties(); - const required_1 = require_required(); - const limitItems_1 = require_limitItems(); - const uniqueItems_1 = require_uniqueItems(); - const const_1 = require_const(); - const enum_1 = require_enum(); - const validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { - keyword: "type", - schemaType: ["string", "array"] - }, - { - keyword: "nullable", - schemaType: "boolean" - }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const def = { - keyword: "items", - type: "array", - schemaType: [ - "object", - "array", - "boolean" - ], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const items_1 = require_items(); - const def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const additionalItems_1 = require_additionalItems(); - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else min = 1; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ - min, - max - }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); - else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) gen.assign(valid, true); - else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - const def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) gen.if(hasProperty, () => { - for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); - }); - else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: prop - }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const util_1 = require_util(); - const def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) additionalPropertyCode(key); - else gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - else definedProp = codegen_1.nil; - if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const validate_1 = require_validate(); - const code_1 = require_code(); - const util_1 = require_util(); - const additionalProperties_1 = require_additionalProperties(); - const def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) it.definedProperties.add(prop); - if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) applyPropertySchema(prop); - else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const util_2 = require_util(); - const def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) checkMatchingProperties(pat); - if (it.allErrors) validateProperties(pat); - else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); - else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: require_code().validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); - else schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - const schCxt = cxt.subschema({ - keyword: "allOf", - schemaProp: i - }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) gen.if(schValid, validateClause("then")); - else gen.if((0, codegen_1.not)(schValid), validateClause("else")); - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const additionalItems_1 = require_additionalItems(); - const prefixItems_1 = require_prefixItems(); - const items_1 = require_items(); - const items2020_1 = require_items2020(); - const contains_1 = require_contains(); - const dependencies_1 = require_dependencies(); - const propertyNames_1 = require_propertyNames(); - const additionalProperties_1 = require_additionalProperties(); - const properties_1 = require_properties(); - const patternProperties_1 = require_patternProperties(); - const not_1 = require_not(); - const anyOf_1 = require_anyOf(); - const oneOf_1 = require_oneOf(); - const allOf_1 = require_allOf(); - const if_1 = require_if(); - const thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); - else applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self } = it; - if (!opts.validateFormats) return; - if ($data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { - key: schema, - ref: fmtDef, - code - }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ - fmtDef.type || "string", - fmtDef.validate, - (0, codegen_1._)`${fmt}.validate` - ]; - return [ - "string", - fmtDef, - fmt - ]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const format = [require_format$2().default]; - exports.default = format; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError) { - DiscrError["Tag"] = "tag"; - DiscrError["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const types_1 = require_types(); - const compile_1 = require_compile(); - const ref_error_1 = require_ref_error(); - const util_1 = require_util(); - const def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); - const tagName = schema.propertyName; - if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); - if (schema.mapping) throw new Error("discriminator: mapping is not supported"); - if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { - discrError: types_1.DiscrError.Tag, - tag, - tagName - })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { - discrError: types_1.DiscrError.Mapping, - tag, - tagName - }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp - }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; - if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required }) { - return Array.isArray(required) && required.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) addMapping(sch.const, i); - else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); - else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "http://json-schema.org/draft-07/schema#", - "title": "Core schema meta-schema", - "definitions": { - "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$ref": "#" } - }, - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - }, - "type": ["object", "boolean"], - "properties": { - "$id": { - "type": "string", - "format": "uri-reference" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "$ref": { - "type": "string", - "format": "uri-reference" - }, - "$comment": { "type": "string" }, - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "readOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - }, - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, - "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "additionalItems": { "$ref": "#" }, - "items": { - "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], - "default": true - }, - "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, - "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "contains": { "$ref": "#" }, - "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, - "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/definitions/stringArray" }, - "additionalProperties": { "$ref": "#" }, - "definitions": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "properties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependencies": { - "type": "object", - "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } - }, - "propertyNames": { "$ref": "#" }, - "const": true, - "enum": { - "type": "array", - "items": true, - "minItems": 1, - "uniqueItems": true - }, - "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/definitions/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "format": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "if": { "$ref": "#" }, - "then": { "$ref": "#" }, - "else": { "$ref": "#" }, - "allOf": { "$ref": "#/definitions/schemaArray" }, - "anyOf": { "$ref": "#/definitions/schemaArray" }, - "oneOf": { "$ref": "#/definitions/schemaArray" }, - "not": { "$ref": "#" } - }, - "default": true - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const discriminator_1 = require_discriminator(); - const draft7MetaSchema = require_json_schema_draft_07(); - const META_SUPPORT_DATA = ["/properties"]; - const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv = Ajv; - module.exports = exports = Ajv; - module.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js -var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicAnchor = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicAnchor", - schemaType: "string", - code: (cxt) => dynamicAnchor(cxt, cxt.schema) - }; - function dynamicAnchor(cxt, anchor) { - const { gen, it } = cxt; - it.schemaEnv.root.dynamicAnchors[anchor] = true; - const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; - const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); - gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); - } - exports.dynamicAnchor = dynamicAnchor; - function _getValidate(cxt) { - const { schemaEnv, schema, self } = cxt.it; - const { root, baseId, localRefs, meta } = schemaEnv.root; - const { schemaId } = self.opts; - const sch = new compile_1.SchemaEnv({ - schema, - schemaId, - root, - baseId, - localRefs, - meta - }); - compile_1.compileSchema.call(self, sch); - return (0, ref_1.getValidate)(cxt, sch); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js -var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicRef = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicRef", - schemaType: "string", - code: (cxt) => dynamicRef(cxt, cxt.schema) - }; - function dynamicRef(cxt, ref) { - const { gen, keyword, it } = cxt; - if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); - const anchor = ref.slice(1); - if (it.allErrors) _dynamicRef(); - else { - const valid = gen.let("valid", false); - _dynamicRef(valid); - cxt.ok(valid); - } - function _dynamicRef(valid) { - if (it.schemaEnv.root.dynamicAnchors[anchor]) { - const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); - gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); - } else _callRef(it.validateName, valid)(); - } - function _callRef(validate, valid) { - return valid ? () => gen.block(() => { - (0, ref_1.callRef)(cxt, validate); - gen.let(valid, true); - }) : () => (0, ref_1.callRef)(cxt, validate); - } - } - exports.dynamicRef = dynamicRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js -var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const util_1 = require_util(); - const def = { - keyword: "$recursiveAnchor", - schemaType: "boolean", - code(cxt) { - if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); - else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js -var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicRef_1 = require_dynamicRef(); - const def = { - keyword: "$recursiveRef", - schemaType: "string", - code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js -var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const dynamicRef_1 = require_dynamicRef(); - const recursiveAnchor_1 = require_recursiveAnchor(); - const recursiveRef_1 = require_recursiveRef(); - const dynamic = [ - dynamicAnchor_1.default, - dynamicRef_1.default, - recursiveAnchor_1.default, - recursiveRef_1.default - ]; - exports.default = dynamic; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js -var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentRequired", - type: "object", - schemaType: "object", - error: dependencies_1.error, - code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js -var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentSchemas", - type: "object", - schemaType: "object", - code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js -var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["maxContains", "minContains"], - type: "array", - schemaType: "number", - code({ keyword, parentSchema, it }) { - if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js -var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependentRequired_1 = require_dependentRequired(); - const dependentSchemas_1 = require_dependentSchemas(); - const limitContains_1 = require_limitContains(); - const next = [ - dependentRequired_1.default, - dependentSchemas_1.default, - limitContains_1.default - ]; - exports.default = next; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js -var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const def = { - keyword: "unevaluatedProperties", - type: "object", - schemaType: ["boolean", "object"], - trackErrors: true, - error: { - message: "must NOT have unevaluated properties", - params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` - }, - code(cxt) { - const { gen, schema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, props } = it; - if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); - else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); - it.props = true; - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function unevaluatedPropCode(key) { - if (schema === false) { - cxt.setParams({ unevaluatedProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (!(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "unevaluatedProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - function unevaluatedDynamic(evaluatedProps, key) { - return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; - } - function unevaluatedStatic(evaluatedProps, key) { - const ps = []; - for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); - return (0, codegen_1.and)(...ps); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js -var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "unevaluatedItems", - type: "array", - schemaType: ["boolean", "object"], - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - const items = it.items || 0; - if (items === true) return; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items }); - cxt.fail((0, codegen_1._)`${len} > ${items}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); - cxt.ok(valid); - } - it.items = true; - function validateItems(valid, from) { - gen.forRange("i", from, len, (i) => { - cxt.subschema({ - keyword: "unevaluatedItems", - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js -var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const unevaluatedProperties_1 = require_unevaluatedProperties(); - const unevaluatedItems_1 = require_unevaluatedItems(); - const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; - exports.default = unevaluated; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json -var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/schema", - "$vocabulary": { - "https://json-schema.org/draft/2019-09/vocab/core": true, - "https://json-schema.org/draft/2019-09/vocab/applicator": true, - "https://json-schema.org/draft/2019-09/vocab/validation": true, - "https://json-schema.org/draft/2019-09/vocab/meta-data": true, - "https://json-schema.org/draft/2019-09/vocab/format": false, - "https://json-schema.org/draft/2019-09/vocab/content": true - }, - "$recursiveAnchor": true, - "title": "Core and Validation specifications meta-schema", - "allOf": [ - { "$ref": "meta/core" }, - { "$ref": "meta/applicator" }, - { "$ref": "meta/validation" }, - { "$ref": "meta/meta-data" }, - { "$ref": "meta/format" }, - { "$ref": "meta/content" } - ], - "type": ["object", "boolean"], - "properties": { - "definitions": { - "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - }, - "dependencies": { - "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", - "type": "object", - "additionalProperties": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "meta/validation#/$defs/stringArray" }] } - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json -var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/applicator", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, - "$recursiveAnchor": true, - "title": "Applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "additionalItems": { "$recursiveRef": "#" }, - "unevaluatedItems": { "$recursiveRef": "#" }, - "items": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "#/$defs/schemaArray" }] }, - "contains": { "$recursiveRef": "#" }, - "additionalProperties": { "$recursiveRef": "#" }, - "unevaluatedProperties": { "$recursiveRef": "#" }, - "properties": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependentSchemas": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" } - }, - "propertyNames": { "$recursiveRef": "#" }, - "if": { "$recursiveRef": "#" }, - "then": { "$recursiveRef": "#" }, - "else": { "$recursiveRef": "#" }, - "allOf": { "$ref": "#/$defs/schemaArray" }, - "anyOf": { "$ref": "#/$defs/schemaArray" }, - "oneOf": { "$ref": "#/$defs/schemaArray" }, - "not": { "$recursiveRef": "#" } - }, - "$defs": { "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$recursiveRef": "#" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json -var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/content", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, - "$recursiveAnchor": true, - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "contentSchema": { "$recursiveRef": "#" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json -var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/core", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, - "$recursiveAnchor": true, - "title": "Core vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "$id": { - "type": "string", - "format": "uri-reference", - "$comment": "Non-empty fragments not allowed.", - "pattern": "^[^#]*#?$" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "$anchor": { - "type": "string", - "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" - }, - "$ref": { - "type": "string", - "format": "uri-reference" - }, - "$recursiveRef": { - "type": "string", - "format": "uri-reference" - }, - "$recursiveAnchor": { - "type": "boolean", - "default": false - }, - "$vocabulary": { - "type": "object", - "propertyNames": { - "type": "string", - "format": "uri" - }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json -var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/format", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, - "$recursiveAnchor": true, - "title": "Format vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json -var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, - "$recursiveAnchor": true, - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json -var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/validation", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, - "$recursiveAnchor": true, - "title": "Validation vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, - "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, - "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, - "minContains": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 1 - }, - "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, - "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/$defs/stringArray" }, - "dependentRequired": { - "type": "object", - "additionalProperties": { "$ref": "#/$defs/stringArray" } - }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] } - }, - "$defs": { - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 0 - }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js -var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema$1(); - const applicator = require_applicator$1(); - const content = require_content$1(); - const core = require_core$1(); - const format = require_format(); - const metadata = require_meta_data$1(); - const validation = require_validation$1(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2019($data) { - [ - metaSchema, - applicator, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2019; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js -var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const discriminator_1 = require_discriminator(); - const json_schema_2019_09_1 = require_json_schema_2019_09(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; - var Ajv2019 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - this.addVocabulary(dynamic_1.default); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - this.addVocabulary(next_1.default); - this.addVocabulary(unevaluated_1.default); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2019_09_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2019 = Ajv2019; - module.exports = exports = Ajv2019; - module.exports.Ajv2019 = Ajv2019; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2019; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js -var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft2020Vocabularies = [ - dynamic_1.default, - core_1.default, - validation_1.default, - (0, applicator_1.default)(true), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary, - next_1.default, - unevaluated_1.default - ]; - exports.default = draft2020Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json -var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/schema", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/core": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true, - "https://json-schema.org/draft/2020-12/vocab/meta-data": true, - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$dynamicAnchor": "meta", - "title": "Core and Validation specifications meta-schema", - "allOf": [ - { "$ref": "meta/core" }, - { "$ref": "meta/applicator" }, - { "$ref": "meta/unevaluated" }, - { "$ref": "meta/validation" }, - { "$ref": "meta/meta-data" }, - { "$ref": "meta/format-annotation" }, - { "$ref": "meta/content" } - ], - "type": ["object", "boolean"], - "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", - "properties": { - "definitions": { - "$comment": "\"definitions\" has been replaced by \"$defs\".", - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "deprecated": true, - "default": {} - }, - "dependencies": { - "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", - "type": "object", - "additionalProperties": { "anyOf": [{ "$dynamicRef": "#meta" }, { "$ref": "meta/validation#/$defs/stringArray" }] }, - "deprecated": true, - "default": {} - }, - "$recursiveAnchor": { - "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", - "$ref": "meta/core#/$defs/anchorString", - "deprecated": true - }, - "$recursiveRef": { - "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", - "$ref": "meta/core#/$defs/uriReferenceString", - "deprecated": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json -var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/applicator", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, - "$dynamicAnchor": "meta", - "title": "Applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "prefixItems": { "$ref": "#/$defs/schemaArray" }, - "items": { "$dynamicRef": "#meta" }, - "contains": { "$dynamicRef": "#meta" }, - "additionalProperties": { "$dynamicRef": "#meta" }, - "properties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependentSchemas": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "propertyNames": { "$dynamicRef": "#meta" }, - "if": { "$dynamicRef": "#meta" }, - "then": { "$dynamicRef": "#meta" }, - "else": { "$dynamicRef": "#meta" }, - "allOf": { "$ref": "#/$defs/schemaArray" }, - "anyOf": { "$ref": "#/$defs/schemaArray" }, - "oneOf": { "$ref": "#/$defs/schemaArray" }, - "not": { "$dynamicRef": "#meta" } - }, - "$defs": { "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$dynamicRef": "#meta" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json -var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, - "$dynamicAnchor": "meta", - "title": "Unevaluated applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "unevaluatedItems": { "$dynamicRef": "#meta" }, - "unevaluatedProperties": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json -var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/content", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, - "$dynamicAnchor": "meta", - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentEncoding": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentSchema": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json -var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/core", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, - "$dynamicAnchor": "meta", - "title": "Core vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "$id": { - "$ref": "#/$defs/uriReferenceString", - "$comment": "Non-empty fragments not allowed.", - "pattern": "^[^#]*#?$" - }, - "$schema": { "$ref": "#/$defs/uriString" }, - "$ref": { "$ref": "#/$defs/uriReferenceString" }, - "$anchor": { "$ref": "#/$defs/anchorString" }, - "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, - "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, - "$vocabulary": { - "type": "object", - "propertyNames": { "$ref": "#/$defs/uriString" }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" } - } - }, - "$defs": { - "anchorString": { - "type": "string", - "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" - }, - "uriString": { - "type": "string", - "format": "uri" - }, - "uriReferenceString": { - "type": "string", - "format": "uri-reference" - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json -var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, - "$dynamicAnchor": "meta", - "title": "Format vocabulary meta-schema for annotation results", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json -var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, - "$dynamicAnchor": "meta", - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json -var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/validation", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, - "$dynamicAnchor": "meta", - "title": "Validation vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, - "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, - "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, - "minContains": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 1 - }, - "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, - "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/$defs/stringArray" }, - "dependentRequired": { - "type": "object", - "additionalProperties": { "$ref": "#/$defs/stringArray" } - } - }, - "$defs": { - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 0 - }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js -var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema(); - const applicator = require_applicator(); - const unevaluated = require_unevaluated(); - const content = require_content(); - const core = require_core(); - const format = require_format_annotation(); - const metadata = require_meta_data(); - const validation = require_validation(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2020($data) { - [ - metaSchema, - applicator, - unevaluated, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2020; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js -var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; - const core_1 = require_core$3(); - const draft2020_1 = require_draft2020(); - const discriminator_1 = require_discriminator(); - const json_schema_2020_12_1 = require_json_schema_2020_12(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; - var Ajv2020 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - draft2020_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2020_12_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2020 = Ajv2020; - module.exports = exports = Ajv2020; - module.exports.Ajv2020 = Ajv2020; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2020; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { - validate, - compare - }; - } - exports.fullFormats = { - date: fmtDef(date, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, - "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, - "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, - "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, - byte, - int32: { - type: "number", - validate: validateInt32 - }, - int64: { - type: "number", - validate: validateInt64 - }, - float: { - type: "number", - validate: validateNumber - }, - double: { - type: "number", - validate: validateNumber - }, - password: true, - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - const DAYS = [ - 0, - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - ]; - function date(str) { - const matches = DATE.exec(str); - if (!matches) return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) return void 0; - if (d1 > d2) return 1; - if (d1 < d2) return -1; - return 0; - } - const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time(str) { - const matches = TIME.exec(str); - if (!matches) return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; - if (hr <= 23 && min <= 59 && sec < 60) return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) return void 0; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) return void 0; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) return 1; - if (t1 < t2) return -1; - return 0; - } - const DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) return void 0; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) return void 0; - return res || compareTime(t1, t2); - } - const NOT_URI_FRAGMENT = /\/|:/; - const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - const MIN_INT32 = -(2 ** 31); - const MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - const Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - const ajv_1 = require_ajv(); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - formatMaximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - formatMinimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - formatExclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - formatExclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self } = it; - if (!opts.validateFormats) return; - const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); - if (fCxt.$data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self.formats[format]; - if (!fmtDef || fmtDef === true) return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - const formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const formats_1 = require_formats(); - const limit_1 = require_limit(); - const codegen_1 = require_codegen(); - const fullName = new codegen_1.Name("fullFormats"); - const fastName = new codegen_1.Name("fastFormats"); - const formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); - if (opts.keywords) (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; - if (!f) throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) ajv.addFormat(f, fs[f]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; -})); - -//#endregion -//#region ../core-internal/src/validators/ajvProvider.ts -var import_ajv = require_ajv(); -var import__2019 = require__2019(); -var import__2020 = require__2020(); -var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); -/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ -const ajvProvider_CEoC_sr_addFormats = import_dist.default; -function createDefaultAjvInstance(engineClass) { - const ajv = new engineClass({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - ajvProvider_CEoC_sr_addFormats(ajv); - return ajv; -} -/** -* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` -* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). -* -* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` -* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class -* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv -* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching -* v1's default engine), while the cfworker provider ignores them per spec. -* Schemas declaring any other `$schema` are -* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate -* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type -* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 -* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and -* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would -* silently downgrade dialect. -* -* @example Use with default configuration -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" -* const validator = new AjvJsonSchemaValidator(); -* ``` -* -* @example Use with a custom AJV instance -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -* -* @example Register ajv-formats -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -*/ -var AjvJsonSchemaValidator = class { - _ajv; - /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ - _ajvDraft7; - /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ - _ajv2019; - /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ - _userAjv; - /** - * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is - * used for **every** schema regardless of its declared `$schema` (the caller owns dialect - * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, - * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with - * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so - * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never - * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter - * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. - */ - constructor(ajv) { - this._userAjv = ajv !== void 0; - this._ajv = ajv; - } - /** The underlying 2020-12 engine — the default instance is created on first use. */ - get ajv() { - return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); - } - /** - * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for - * every schema — do not second-guess by `$schema` (bring-your-own-validator means - * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → - * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. - */ - _engineFor(schema) { - if (this._userAjv) return this.ajv; - const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); - if (dialect === "2020-12") return this.ajv; - if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); - return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); - } - getValidator(schema) { - const engine = this._engineFor(schema); - const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); - return (input) => { - return ajvValidator(input) ? { - valid: true, - data: input, - errorMessage: void 0 - } : { - valid: false, - data: void 0, - errorMessage: engine.errorsText(ajvValidator.errors) - }; - }; - } -}; -/** -* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. -* The full v1-equivalent construction is: -* -* ```ts -* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* new AjvJsonSchemaValidator(ajv); -* ``` -* -* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque -* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` -* validation that the v1 default had). -* -* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream -* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own -* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. -*/ -const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; - -//#endregion - -//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map - - - - - - - - -//#region src/server/completable.ts -const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); -/** -* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. -* -* @example -* ```ts source="./completable.examples.ts#completable_basicUsage" -* server.registerPrompt( -* 'review-code', -* { -* title: 'Code Review', -* argsSchema: z.object({ -* language: completable(z.string().describe('Programming language'), value => -* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) -* ) -* }) -* }, -* ({ language }) => ({ -* messages: [ -* { -* role: 'user' as const, -* content: { -* type: 'text' as const, -* text: `Review this ${language} code.` -* } -* } -* ] -* }) -* ); -* ``` -* -* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions -*/ -function completable(schema, complete) { - Object.defineProperty(schema, COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** -* Checks if a schema is completable (has completion metadata). -*/ -function isCompletable(schema) { - return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; -} -/** -* Gets the completer callback from a completable schema, if it exists. -*/ -function getCompleter(schema) { - return schema[COMPLETABLE_SYMBOL]?.complete; -} - -//#endregion -//#region src/server/sseKeepAlive.ts -/** Default interval between SSE keep-alive comment frames. */ -const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; -const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); -/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ -function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { - if (!Number.isFinite(intervalMs) || intervalMs < 1) return; - const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); - timer.unref?.(); - return timer; -} - -//#endregion -//#region src/server/serverEventBus.ts -/** -* A `ServerEventBus` backed by an in-process listener set. -* -* `publish()` delivers synchronously to the live listener set (a listener -* unsubscribing itself mid-dispatch is safe; the entry's listen-router -* listeners never unsubscribe peers). A throwing listener does not stop -* delivery to the others. -*/ -var mcp_DXXb3Vv3_InMemoryServerEventBus = class { - _listeners = /* @__PURE__ */ new Set(); - /** - * @param onerror - Optional callback for errors thrown by listeners - * during dispatch. - */ - constructor(onerror) { - this.onerror = onerror; - } - publish(event) { - for (const listener of this._listeners) try { - listener(event); - } catch (error) { - this.onerror?.(error instanceof Error ? error : new Error(String(error))); - } - } - subscribe(listener) { - this._listeners.add(listener); - let live = true; - return () => { - if (!live) return; - live = false; - this._listeners.delete(listener); - }; - } - /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ - get listenerCount() { - return this._listeners.size; - } -}; -/** Build a {@linkcode ServerNotifier} over a bus. */ -function mcp_DXXb3Vv3_createServerNotifier(bus) { - return { - toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), - promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), - resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), - resourceUpdated: (uri) => bus.publish({ - kind: "resource_updated", - uri - }) - }; -} -/** -* Whether a `subscriptions/listen` filter accepts a given change event. -* -* Pure: no I/O, no mutation. The filter governs ONLY the four -* subscription-gated change types — non-gated notifications never reach the -* bus and are not modeled here. -* -* `resource_updated` matches only when `resourceSubscriptions` is present and -* contains the event's URI exactly (per the spec: "for these resource URIs"). -*/ -function listenFilterAccepts(filter, event) { - switch (event.kind) { - case "tools_list_changed": return filter.toolsListChanged === true; - case "prompts_list_changed": return filter.promptsListChanged === true; - case "resources_list_changed": return filter.resourcesListChanged === true; - case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); - } -} -/** -* The honored subset of a requested filter: keeps only the fields the client -* explicitly opted in to (drops `false` and absent fields), narrowed against -* the server's declared capabilities when supplied. The serving entry sends -* this back in `notifications/subscriptions/acknowledged` so the ack reflects -* what the server can actually deliver. -* -* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` -* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. -* - `resourceSubscriptions` is honored only when -* `capabilities.resources.subscribe` is advertised. -* -* `capabilities` is optional on this pure helper for test convenience only — -* both wired routers REQUIRE capabilities at the call site (the HTTP router's -* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws -* before `setServerCapabilities()` was called), so the fail-open -* `undefined → honor everything` branch is never reachable on a wired entry. -*/ -function honoredSubset(requested, capabilities) { - const honored = {}; - const allow = (bit) => capabilities === void 0 || bit === true; - if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; - if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; - if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; - if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; - return honored; -} -/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ -function serverEventToNotification(event) { - switch (event.kind) { - case "tools_list_changed": return { method: "notifications/tools/list_changed" }; - case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; - case "resources_list_changed": return { method: "notifications/resources/list_changed" }; - case "resource_updated": return { - method: "notifications/resources/updated", - params: { uri: event.uri } - }; - } -} - -//#endregion -//#region src/server/listenRouter.ts -/** Default capacity guard: refuse a new subscription when this many are already open. */ -const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; -function jsonRpcError(id, code, message) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message - }, - id - }, { status: 200 }); -} -/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ -function stampSubscriptionId(notification, subscriptionId) { - return { - method: notification.method, - params: { - ...notification.params, - _meta: { - ...notification.params?._meta, - [SUBSCRIPTION_ID_META_KEY]: subscriptionId - } - } - }; -} -/** -* Read the requested filter off a `subscriptions/listen` request body. -* Returns the validated filter, or `undefined` when `params.notifications` -* is absent or fails the schema (the caller answers `-32602` — the spec -* marks `notifications` REQUIRED on the listen request). -*/ -function parseListenFilter(message) { - const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); - return outcome.ok ? outcome.value.params?.notifications : void 0; -} -function mcp_DXXb3Vv3_createListenRouter(options) { - const { bus, onerror } = options; - const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; - const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; - const open = /* @__PURE__ */ new Set(); - function serve(message, signal, capabilities, serverInfo) { - if (open.size >= maxSubscriptions) { - onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); - return jsonRpcError(message.id, -32603, "Subscription limit reached"); - } - const filter = parseListenFilter(message); - if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); - const honored = honoredSubset(filter, capabilities); - const subscriptionId = message.id; - const encoder = new TextEncoder(); - let controller; - let closed = false; - let unsubscribe; - let keepAliveTimer; - let abortCleanup; - const writeFrame = (frame) => { - if (closed) return; - try { - controller.enqueue(encoder.encode(frame)); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - }; - const writeNotification = (method, params) => { - writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - method, - params - })}\n\n`); - }; - const teardown = (graceful) => { - if (closed) return; - if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - id: subscriptionId, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: subscriptionId, - [SERVER_INFO_META_KEY]: serverInfo - } - } - })}\n\n`); - closed = true; - try { - unsubscribe?.(); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - abortCleanup?.(); - open.delete(teardown); - try { - controller.close(); - } catch {} - }; - const readable = new ReadableStream({ - start(streamController) { - controller = streamController; - const ack = stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, subscriptionId); - writeNotification(ack.method, ack.params); - unsubscribe = bus.subscribe((event) => { - if (closed || !listenFilterAccepts(honored, event)) return; - const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); - writeNotification(note.method, note.params); - }); - keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); - open.add(teardown); - }, - cancel() { - teardown(false); - } - }); - if (signal !== void 0) if (signal.aborted) teardown(false); - else { - const onAbort = () => teardown(false); - signal.addEventListener("abort", onAbort, { once: true }); - abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - return new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - }); - } - return { - serve, - closeAll() { - for (const teardown of open) teardown(true); - }, - get openCount() { - return open.size; - } - }; -} -const CHANGE_NOTIFICATION_METHODS = new Set([ - "notifications/tools/list_changed", - "notifications/prompts/list_changed", - "notifications/resources/list_changed", - "notifications/resources/updated" -]); -/** -* Per-connection listen state for the stdio entry. One instance is held by -* `serveStdio` for the connection lifetime; it routes inbound -* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound -* change notifications onto the active subscriptions. No bus — the long-lived -* pinned instance's existing `send*ListChanged()` calls feed straight into -* `routeOutbound()`. -*/ -var mcp_DXXb3Vv3_StdioListenRouter = class { - /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ - _subs = /* @__PURE__ */ new Map(); - /** - * The serving instance's declared capabilities. Filled in by the entry - * once the modern instance is constructed (the router is created before - * the instance exists), so the acknowledged filter is narrowed against - * what the server can actually deliver. - */ - _serverCapabilities; - /** - * The serving instance's identity, stamped onto the graceful-close - * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends - * `ResultMetaObject`). Handed over together with the capabilities. - */ - _serverInfo; - constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { - this._maxSubscriptions = _maxSubscriptions; - this._serverCapabilities = serverCapabilities; - this._serverInfo = serverInfo; - } - /** - * Record the serving instance's declared capabilities and identity once - * it has been constructed. Called by `serveStdio`'s connect path; - * subsequent `serve()` calls narrow the honored filter against the - * capabilities, and `teardownAll()` stamps the identity. - */ - setServerCapabilities(capabilities, serverInfo) { - this._serverCapabilities = capabilities; - if (serverInfo !== void 0) this._serverInfo = serverInfo; - } - /** Whether `id` is an active listen subscription on this connection. */ - has(id) { - return this._subs.has(id); - } - /** - * Serve one inbound `subscriptions/listen` request: registers the - * subscription and returns the stamped acknowledged notification (or, on - * capacity / params rejection, the in-band JSON-RPC error response). - * - * @throws when called before {@linkcode setServerCapabilities} (or the - * constructor) has supplied the serving instance's capabilities. Honoring a - * filter without knowing the server's advertised capabilities would fail - * open (deliver unadvertised types); the entry guarantees capabilities are - * set before any listen request is routed here. - */ - serve(message) { - if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); - if (this._subs.size >= this._maxSubscriptions) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32603, - message: "Subscription limit reached" - } - }; - const filter = parseListenFilter(message); - if (filter === void 0) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" - } - }; - const honored = honoredSubset(filter, this._serverCapabilities); - this._subs.set(message.id, honored); - return stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, message.id); - } - /** - * Tear down one subscription (inbound `notifications/cancelled`). Returns - * `true` when a subscription was removed. After this call NOTHING further - * is delivered for that subscription id (the post-cancel hardening). - */ - cancel(id) { - return this._subs.delete(id); - } - /** - * Route an outbound notification through the active subscriptions. - * - * - For a subscription-gated change notification, returns one stamped copy - * per subscription that opted in to it (an empty array means it is - * dropped — the modern era never delivers an un-requested change type). - * - For any other outbound message, returns `'passthrough'` (the entry - * forwards it as-is). - */ - routeOutbound(message) { - if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; - const uriParam = message.params?.["uri"]; - const uri = typeof uriParam === "string" ? uriParam : void 0; - const event = notificationToServerEvent(message.method, uri); - const out = []; - for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ - method: message.method, - params: message.params ?? {} - }, subscriptionId)); - return out; - } - /** - * Server-side graceful teardown of every active subscription: returns the - * empty `subscriptions/listen` JSON-RPC result for each subscription id — - * the spec's graceful-close signal, `_meta` carrying the subscription id - * and the serving instance's identity — for the entry to emit before - * closing the wire. Clears the set so nothing further is delivered. - */ - teardownAll() { - const out = []; - for (const id of this._subs.keys()) out.push({ - jsonrpc: "2.0", - id, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: id, - ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } - } - } - }); - this._subs.clear(); - return out; - } -}; -function notificationToServerEvent(method, uri) { - switch (method) { - case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; - case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; - case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; - default: return { - kind: "resource_updated", - uri: uri ?? "" - }; - } -} - -//#endregion -//#region src/server/legacyInputRequiredShim.ts -/** -* Default handler re-entries per originating request — tighter than the -* client driver's 10 because the shim holds a live wire request open. -*/ -const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; -/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ -const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; -/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ -function resolveLegacyShimOptions(options) { - if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); - if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); - return { - maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, - roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, - legacyShim: options?.legacyShim ?? true - }; -} -/** -* Validates one `inputRequests` entry: malformed or unknown kinds are server -* bugs and fail loudly on both eras. Shared by the modern seam's capability -* check and the shim's gate. -*/ -function coerceEmbeddedInputRequest(method, key, entry) { - if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); - const embedded = entry; - const required = requiredClientCapabilitiesForInputRequest(embedded); - if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); - return { - embedded, - required - }; -} -/** -* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 -* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a -* getRandomValues fallback for runtimes without `randomUUID`). -*/ -function syntheticElicitationId() { - const webCrypto = globalThis.crypto; - if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); - const bytes = new Uint8Array(16); - webCrypto.getRandomValues(bytes); - bytes[6] = bytes[6] & 15 | 64; - bytes[8] = bytes[8] & 63 | 128; - const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} -/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ -function legacyShimFailure(method, message) { - if (method === "tools/call") return { - content: [{ - type: "text", - text: message - }], - isError: true - }; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); -} -/** The fulfilment loop — see the module doc for the contract. */ -var LegacyInputRequiredShim = class { - constructor(_host) { - this._host = _host; - } - async fulfill(method, handler, request, ctx, firstResult) { - const { maxRounds, roundTimeoutMs } = this._host; - const outerSignal = ctx.mcpReq.signal; - let current = firstResult; - let round = 0; - while (true) { - round += 1; - if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); - const inputRequests = current.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const requestState = typeof current.requestState === "string" ? current.requestState : void 0; - if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - let responses; - if (hasInputRequests) { - const declared = this._host.resolvedClientCapabilities(ctx); - const coerced = []; - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); - if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); - coerced.push([key, embedded]); - } - const roundAbort = linkedRoundAbort(outerSignal); - try { - const legOptions = { - relatedRequestId: ctx.mcpReq.id, - timeout: roundTimeoutMs, - resetTimeoutOnProgress: true, - onprogress: () => {}, - signal: roundAbort.signal - }; - const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { - try { - return [key, await this._dispatchLeg(embedded, legOptions)]; - } catch (error) { - roundAbort.abort(error); - throw error; - } - })); - responses = Object.fromEntries(fulfilled); - } catch (error) { - if (outerSignal.aborted) throw error; - return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); - } finally { - roundAbort.dispose(); - } - } else await sleep((/* inlined export .C */250), outerSignal); - let ctxNext = { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - inputResponses: responses, - droppedInputResponseKeys: void 0, - requestState: requestStateAccessor(requestState) - } - }; - if (requestState !== void 0) { - const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); - if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); - } - const next = await handler(request, ctxNext); - if (!isInputRequiredResult(next)) return next; - current = next; - } - } - /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ - async _dispatchLeg(embedded, options) { - switch (embedded.method) { - case "elicitation/create": { - let params = embedded.params; - if (params.mode === "url" && params.elicitationId === void 0) params = { - ...params, - elicitationId: syntheticElicitationId() - }; - return await this._host.sendElicitation(params, options); - } - case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); - case "roots/list": return await this._host.listRoots(embedded.params, options); - } - } -}; - -//#endregion -//#region src/server/server.ts -/** -* The request methods whose 2026-07-28 result vocabulary includes -* `input_required` (the multi round-trip methods). Returning an -* input-required result from any other handler is a server bug. -*/ -const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ - "tools/call", - "prompts/get", - "resources/read" -]); -let writeClientIdentity; -let installDiscoverHandler; -let readServerIdentity; -/** -* Package-internal: backfills the connection-scoped client-identity fields of a -* per-request server instance from the request's validated `_meta` envelope, so the -* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} -* accessors keep answering on instances that never see an `initialize` handshake. -* Not public API. -*/ -function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { - writeClientIdentity(server, identity); -} -/** -* Package-internal: installs the modern-only `server/discover` handler on an instance -* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern -* revisions the entry serves appear in the instance's supported-versions list (so the -* discover advertisement and version-mismatch errors name them). Idempotent. -* Hand-constructed instances are unaffected: nothing else calls this, so they keep -* answering `-32601` unless their own supported-versions list opts into a modern -* revision. Not public API. -*/ -function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { - installDiscoverHandler(server, servedModernVersions); -} -/** -* Package-internal: the instance's implementation identity, for the serving -* entries to stamp onto entry-built results (the `subscriptions/listen` -* graceful-close result — built outside the encode seam, but the spec's -* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries -* the serverInfo SHOULD like every other result). Not public API. -*/ -function mcp_DXXb3Vv3_serverIdentityOf(server) { - return readServerIdentity(server); -} -/** -* An MCP server on top of a pluggable transport. -* -* This server will automatically respond to the initialization flow as initiated from the client. -* -* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. -*/ -var Server = class extends Protocol { - _clientCapabilities; - _clientVersion; - static { - writeClientIdentity = (server, identity) => { - if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; - if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; - }; - installDiscoverHandler = (server, servedModernVersions) => { - const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); - if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; - server.setRequestHandler("server/discover", () => server._ondiscover()); - }; - readServerIdentity = (server) => server._serverInfo; - } - _capabilities; - _instructions; - _jsonSchemaValidator; - _cacheHints; - _requestStateVerify; - _inputRequiredServing; - _legacyShim; - /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ - _legacyInputRequiredShim() { - return this._legacyShim ??= new LegacyInputRequiredShim({ - maxRounds: this._inputRequiredServing.maxRounds, - roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, - resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), - verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), - sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), - sendSampling: (params, options) => this.createMessage(params, options), - listRoots: (params, options) => this.listRoots(params, options) - }); - } - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). - */ - oninitialized; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this._requestStateVerify = options?.requestState?.verify; - this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); - if (options?.cacheHints !== void 0) { - for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); - this._cacheHints = options.cacheHints; - } - this.setRequestHandler("initialize", (request) => this._oninitialize(request)); - this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); - if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); - if (this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Registers the built-in `logging/setLevel` request handler. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - _registerLoggingHandler() { - this.setRequestHandler("logging/setLevel", async (request, ctx) => { - const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; - const { level } = request.params; - const parseResult = parseSchema(LoggingLevelSchema, level); - if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); - return {}; - }); - } - buildContext(ctx, transportInfo) { - const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - log: (level, data, logger) => { - if (!this._capabilities.logging) return Promise.resolve(); - let threshold; - if (this._servedModernEra()) { - threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; - if (threshold === void 0) return Promise.resolve(); - } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); - if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); - return ctx.mcpReq.notify({ - method: "notifications/message", - params: { - level, - data, - logger - } - }); - }, - elicitInput: (params, options) => this.elicitInput(params, options), - requestSampling: (params, options) => this.createMessage(params, options) - }, - http: hasHttpInfo ? { - ...ctx.http, - req: transportInfo?.request, - closeSSE: transportInfo?.closeSSEStream, - closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream - } : void 0 - }; - } - _loggingLevels = /* @__PURE__ */ new Map(); - LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); - const hadLogging = !!this._capabilities.logging; - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Enforces server-side validation for `tools/call` results regardless of how the - * handler was registered, attaches the configured per-operation cache hint - * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` - * for results that do not provide their own, and owns the multi-round-trip - * seam: on the methods whose 2026-07-28 result vocabulary includes - * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an - * input-required return skips result-schema validation and is checked - * against the served era, the at-least-one rule, and the request's own - * declared client capabilities; on every other method an input-required - * return is a server bug and fails loudly. The hint rides a symbol-keyed - * property that is never serialized, so 2025-era responses are unaffected. - */ - _wrapHandler(method, handler) { - if (method !== "tools/call") { - const cacheHint = this._cacheHints?.[method]; - const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); - if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { - const result = await handler(request, ctx); - if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - }; - return async (request, ctx) => { - const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); - if (isInputRequiredResult(result)) { - if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - } - return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); - }; - } - return async (request, ctx) => { - const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - const validatedRequest = codec.validateRequest("tools/call", request); - if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); - const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); - if (isInputRequiredResult(result)) return result; - const normalizedResult = normalizeContentlessToolResult(result); - const validationResult = codec.validateResult("tools/call", normalizedResult); - if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); - return validationResult.value; - }; - } - /** - * Whether this instance is bound to a 2026-07-28-or-later protocol - * revision. Era is instance state — a serving entry (`createMcpHandler`, - * `serveStdio`) marks the instance modern at construction; a 2025-era - * `initialize` handshake binds it legacy. The multi-round-trip seam reads - * this directly: there is no per-request era consult. - */ - _servedModernEra() { - return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); - } - /** - * Invokes a handler for one of the multi-round-trip methods and applies - * the input-required seam: - * - * - a `UrlElicitationRequiredError` (or any 2025-style server→client - * request idiom) escaping the handler on a request served on the - * 2026-07-28 era fails LOUDLY with a clear steer to - * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the - * 2026-07-28 wire and the throw is not silently converted. Requests - * served on the 2025 era keep today's `-32042` behavior byte-exact (the - * error is rethrown unchanged). - * - an input-required RETURN toward a 2026-07-28 request must satisfy - * the at-least-one rule, and every embedded request must be covered by - * the capabilities declared on the request's envelope (violations - * answer the typed `-32021` error). Toward a 2025-era request the - * return is fulfilled by the default-on legacy shim, whose own gate - * consults the initialize-declared capabilities and surfaces - * violations per family; `inputRequired.legacyShim: false` restores - * the pre-shim loud failure. - */ - async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { - const servedModern = this._servedModernEra(); - const rawRequestState = ctx.mcpReq.requestState(); - if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - let ctxForHandler = ctx; - if (typeof rawRequestState === "string") { - const decoded = await this._verifyRequestState(rawRequestState, ctx, method); - if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); - } - let result; - try { - result = await handler(request, ctxForHandler); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { - if (!servedModern) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); - } - throw error; - } - if (!isInputRequiredResult(result)) return result; - if (!servedModern) { - if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); - return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); - } - const inputRequests = result.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const hasRequestState = typeof result.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - if (hasInputRequests) { - const declared = this._inputRequestCapabilityView(ctx); - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); - if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); - } - } - return result; - } - /** - * Runs the configured `requestState.verify` hook and returns its - * resolved value (`undefined` when unconfigured or the hook returns - * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; - * the reason goes to `onerror` only. - */ - async _verifyRequestState(state, ctx, method) { - if (this._requestStateVerify === void 0) return; - try { - return await this._requestStateVerify(state, ctx); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - } - } - /** - * The per-request resolved client-capabilities view: the request's own - * `_meta` envelope on the 2026 era; the `initialize`-declared state on a - * 2025-era connection. Per-request instances that never saw an - * initialize (stateless legacy) hold nothing, so gates refuse there. - */ - _inputRequestCapabilityView(ctx) { - return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; - } - /** - * Guard for the push-style server→client request APIs ({@linkcode createMessage}, - * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a - * modern-era instance: the 2026-07-28 revision has no server→client request - * channel, so the call fails before any wire traffic with a typed error - * whose message steers to `inputRequired(...)`. The base era gate would - * also reject it; this guard runs first to carry the steer. - */ - _assertPushApiInServedEra(method) { - if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { - method, - era: "2026-07-28" - }); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); - break; - case "roots/list": - if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); - break; - case "ping": break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); - break; - case "notifications/cancelled": break; - case "notifications/progress": break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); - break; - case "logging/setLevel": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); - break; - case "ping": - case "initialize": break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); - const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; - this._negotiatedProtocolVersion = protocolVersion; - this.transport?.setProtocolVersion?.(protocolVersion); - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` - * lists only modern revisions (2025-era versions are negotiated via `initialize`); - * the capabilities are advertised as-is, listChanged/subscribe bits included - * (see {@linkcode discoverAdvertisedCapabilities}). - */ - _ondiscover() { - return { - supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), - capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * The identity the 2026-era encode seam stamps into every outbound - * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR - * #3002: servers SHOULD identify themselves on every response). - */ - _outboundServerInfo() { - return this._serverInfo; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * declared capabilities, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * name and version, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientVersion() { - return this._clientVersion; - } - /** - * After initialization has completed, this will be populated with the protocol version negotiated - * with the client (the version the server responded with during the initialize handshake), or - * `undefined` before initialization. - * - * @deprecated Read the protocol revision from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the - * request was sent for, while on 2025-era connections this accessor keeps returning the - * `initialize`-negotiated version. The accessor remains functional — instances serving the - * 2026-07-28 era report that revision. - */ - getNegotiatedProtocolVersion() { - return this._negotiatedProtocolVersion; - } - /** - * Project a `tools/call` result through this instance's negotiated wire - * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on - * the 2025 era the `{result:…}` wrap when `structuredContent` is a - * non-object value or the advertised `outputSchema` had a non-object root. - * Identity for object-shaped `structuredContent` on the 2026 era. - * - * `McpServer`'s built-in `tools/call` handler routes through this method. - * Low-level `setRequestHandler('tools/call', …)` authors call it - * themselves so the projection lives in one place (the codec) and the - * server-side handler stays era-blind. - * - * This is the only codec function exposed on `Server` — the full - * `WireCodec` is intentionally not part of the public surface. - */ - projectCallToolResult(result, advertisedOutputSchema) { - return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); - } - /** - * Returns the current server capabilities. - */ - getCapabilities() { - return this._capabilities; - } - /** - * Sends a `ping` request to the connected client. - * - * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. - * If your factory serves both eras, this only works on the legacy path. - */ - async ping() { - this._assertPushApiInServedEra("ping"); - return this.request({ method: "ping" }); - } - async createMessage(params, options) { - this._assertPushApiInServedEra("sampling/createMessage"); - if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); - if (params.messages.length > 0) { - const lastMessage = params.messages.at(-1); - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); - if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - const hasTools = Boolean(params.tools || params.toolChoice); - const wide = await this.request({ - method: "sampling/createMessage", - params - }, options); - const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); - if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); - return outcome.value; - } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - * - * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) - * instead. The 2025 push-style server-to-client request model is replaced by input_required - * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the - * legacy path. - */ - async elicitInput(params, options) { - this._assertPushApiInServedEra("elicitation/create"); - switch (params.mode ?? "form") { - case "url": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); - break; - case "form": - if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); - break; - } - return this._sendElicitationLeg(params, options); - } - /** - * The capability-check-free core of {@linkcode elicitInput}. The shim - * uses it because its gate differs from the public checks: a bare - * `elicitation: {}` counts as form support (the pre-mode rule), and - * accepted content passes through unvalidated for parity with the - * modern client driver (handlers validate via the schema-aware - * `acceptedContent` overload and can re-ask). - */ - async _sendElicitationLeg(params, options, behavior) { - const mode = params.mode ?? "form"; - const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; - switch (mode) { - case "url": { - const urlParams = params; - return this.request({ - method: "elicitation/create", - params: urlParams - }, options); - } - case "form": { - const formParams = params.mode === "form" ? params : { - ...params, - mode: "form" - }; - const result = await this.request({ - method: "elicitation/create", - params: formParams - }, options); - if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { - const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); - if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * The notification (and the `elicitationId` it references) exists only on protocol revision - * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the - * returned callback rejects with a typed local error before anything reaches the transport - * (the method is not part of that revision's wire registry). - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { elicitationId } - }, options); - } - /** - * Requests the list of roots from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, - * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 - * push-style server-to-client request model is replaced by input_required results in the - * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. - */ - async listRoots(params, options) { - this._assertPushApiInServedEra("roots/list"); - return this.request({ - method: "roots/list", - params - }, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ - method: "notifications/message", - params - }); - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - async sendResourceListChanged() { - return this.notification({ method: "notifications/resources/list_changed" }); - } - async sendToolListChanged() { - return this.notification({ method: "notifications/tools/list_changed" }); - } - async sendPromptListChanged() { - return this.notification({ method: "notifications/prompts/list_changed" }); - } -}; -/** -* The capability set a server advertises on `server/discover`. Pure — never -* mutates the input; the legacy `initialize` advertisement is untouched. -* -* The serving entries serve `subscriptions/listen` themselves, so the -* `listChanged` and `resources.subscribe` capability bits are advertised -* as-is: a modern-era client uses them to decide which notification types to -* request on its listen filter. -*/ -function discoverAdvertisedCapabilities(capabilities) { - return { ...capabilities }; -} - -//#endregion -//#region src/server/mcp.ts -/** -* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. -* For advanced usage (like sending notifications or setting custom request handlers), use the underlying -* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. -* -* @example -* ```ts source="./mcp.examples.ts#McpServer_basicUsage" -* const server = new McpServer({ -* name: 'my-server', -* version: '1.0.0' -* }); -* ``` -*/ -var mcp_DXXb3Vv3_McpServer = class { - /** - * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. - */ - server; - _registeredResources = {}; - _registeredResourceTemplates = {}; - _registeredTools = {}; - _registeredPrompts = {}; - /** - * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 - * registration-time scan and the pre-dispatch validation step share one - * conversion instead of paying it twice per request under the - * per-request-factory `createMcpHandler` model. - */ - _toolInputSchemaJson = {}; - /** - * The JSON-serialized `inputSchema` of a registered tool, or `undefined` - * when no such tool is registered. Used by the HTTP entry's pre-dispatch - * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema - * `tools/list` would emit, before dispatch reaches the handler). - * - * @internal - */ - toolInputSchemaJson(name) { - const tool = this._registeredTools[name]; - if (tool === void 0 || !tool.enabled) return void 0; - if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; - if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; - try { - const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - return json; - } catch { - return; - } - } - constructor(serverInfo, options) { - this.server = new Server(serverInfo, options); - if (options?.capabilities?.tools) this.setToolRequestHandlers(); - if (options?.capabilities?.resources) this.setResourceRequestHandlers(); - if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" - * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); - * const transport = new StdioServerTransport(); - * await server.connect(transport); - * ``` - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - _toolHandlersInitialized = false; - setToolRequestHandlers() { - if (this._toolHandlersInitialized) return; - this.server.assertCanSetRequestHandler("tools/list"); - this.server.assertCanSetRequestHandler("tools/call"); - this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); - this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations, - icons: tool.icons, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); - return toolDefinition; - }) })); - this.server.setRequestHandler("tools/call", async (request, ctx) => { - const tool = this._registeredTools[request.params.name]; - if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - try { - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, ctx); - await this.validateToolOutput(tool, result, request.params.name); - if (isInputRequiredResult(result)) return result; - return this.server.projectCallToolResult(result, tool.outputSchemaJson); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [{ - type: "text", - text: errorMessage - }], - isError: true - }; - } - /** - * Validates tool input arguments against the tool's input schema. - */ - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) return; - const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); - return parseResult.data; - } - /** - * Validates tool output against the tool's output schema. - */ - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) return; - if (isInputRequiredResult(result)) return; - if (result.isError) return; - if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); - } - /** - * Executes a tool handler. - */ - async executeToolHandler(tool, args, ctx) { - return tool.executor(args, ctx); - } - _completionHandlerInitialized = false; - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) return; - this.server.assertCanSetRequestHandler("completion/complete"); - this.server.registerCapabilities({ completions: {} }); - this.server.setRequestHandler("completion/complete", async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; - const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); - if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; - const completer = getCompleter(field); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - _resourceHandlersInitialized = false; - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) return; - this.server.assertCanSetRequestHandler("resources/list"); - this.server.assertCanSetRequestHandler("resources/templates/list"); - this.server.assertCanSetRequestHandler("resources/read"); - this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); - this.server.setRequestHandler("resources/list", async (_request, ctx) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) continue; - const result = await template.resourceTemplate.listCallback(ctx); - for (const resource of result.resources) templateResources.push({ - ...template.metadata, - ...resource - }); - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler("resources/templates/list", async () => { - return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })) }; - }); - this.server.setRequestHandler("resources/read", async (request, ctx) => { - let uri; - try { - uri = new URL(request.params.uri); - } catch { - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { - uri: request.params.uri, - reason: "invalid_uri" - }); - } - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); - return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); - } - throw new ResourceNotFoundError(request.params.uri); - }); - this._resourceHandlersInitialized = true; - } - _promptHandlersInitialized = false; - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) return; - this.server.assertCanSetRequestHandler("prompts/list"); - this.server.assertCanSetRequestHandler("prompts/get"); - this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); - this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, - icons: prompt.icons, - _meta: prompt._meta - }; - }) })); - this.server.setRequestHandler("prompts/get", async (request, ctx) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - return prompt.handler(request.params.arguments, ctx); - }); - this._promptHandlersInitialized = true; - } - registerResource(name, uriOrTemplate, config, readCallback) { - const cacheHint = config.cacheHint; - let metadata = config; - if (cacheHint !== void 0) { - assertValidCacheHint(cacheHint, `resource ${name}`); - const rest = { ...config }; - delete rest.cacheHint; - metadata = rest; - } - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (updates.uri !== void 0 && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) this._registeredResources[updates.uri] = registeredResource; - } - if (updates.name !== void 0) registeredResource.name = updates.name; - if (updates.title !== void 0) registeredResource.title = updates.title; - if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; - if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; - if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { - let currentArgsSchema = argsSchema; - let currentCallback = callback; - const registeredPrompt = { - title, - description, - argsSchema, - icons, - _meta, - handler: createPromptHandler(name, argsSchema, callback), - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; - } - if (updates.title !== void 0) registeredPrompt.title = updates.title; - if (updates.description !== void 0) registeredPrompt.description = updates.description; - if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; - if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; - let needsHandlerRegen = false; - if (updates.argsSchema !== void 0) { - registeredPrompt.argsSchema = updates.argsSchema; - currentArgsSchema = updates.argsSchema; - needsHandlerRegen = true; - } - if (updates.callback !== void 0) { - currentCallback = updates.callback; - needsHandlerRegen = true; - } - if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); - if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - if (argsSchema) { - const shape = getSchemaShape(argsSchema); - if (shape) { - if (Object.values(shape).some((field) => { - return isCompletable(unwrapOptionalSchema(field)); - })) this.setCompletionRequestHandler(); - } - } - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { - validateAndWarnToolName(name); - if (inputSchema !== void 0) try { - const json = standardSchemaToJsonSchema(inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); - if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); - } catch {} - let currentHandler = handler; - const registeredTool = { - title, - description, - inputSchema, - outputSchema, - outputSchemaJson: convertOutputSchemaJson(outputSchema), - annotations, - icons, - execution, - _meta, - handler, - executor: createToolExecutor(inputSchema, handler), - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - if (typeof updates.name === "string") validateAndWarnToolName(updates.name); - delete this._registeredTools[name]; - delete this._toolInputSchemaJson[name]; - if (updates.name) { - delete this._toolInputSchemaJson[updates.name]; - this._registeredTools[updates.name] = registeredTool; - name = updates.name; - } - } - if (updates.title !== void 0) registeredTool.title = updates.title; - if (updates.description !== void 0) registeredTool.description = updates.description; - let needsExecutorRegen = false; - if (updates.paramsSchema !== void 0) { - registeredTool.inputSchema = updates.paramsSchema; - delete this._toolInputSchemaJson[name]; - needsExecutorRegen = true; - } - if (updates.callback !== void 0) { - registeredTool.handler = updates.callback; - currentHandler = updates.callback; - needsExecutorRegen = true; - } - if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); - if (updates.outputSchema !== void 0) { - registeredTool.outputSchema = updates.outputSchema; - registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); - } - if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; - if (updates.icons !== void 0) registeredTool.icons = updates.icons; - if (updates._meta !== void 0) registeredTool._meta = updates._meta; - if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - registerTool(name, config, cb) { - if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); - const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; - return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); - } - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); - const { title, description, argsSchema, icons, _meta } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns `true` if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" - * await server.sendLoggingMessage({ - * level: 'info', - * data: 'Processing complete' - * }); - * ``` - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) this.server.sendResourceListChanged(); - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) this.server.sendToolListChanged(); - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) this.server.sendPromptListChanged(); - } -}; -/** -* A resource template combines a URI pattern with optional functionality to enumerate -* all resources matching that pattern. -*/ -var ResourceTemplate = class { - _uriTemplate; - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - return this._callbacks.complete?.[variable]; - } -}; -/** -* Creates an executor that invokes the handler with the appropriate arguments. -* When `inputSchema` is defined, the handler is called with `(args, ctx)`. -* When `inputSchema` is undefined, the handler is called with just `(ctx)`. -*/ -function createToolExecutor(inputSchema, handler) { - if (inputSchema) { - const callback$1 = handler; - return async (args, ctx) => callback$1(args, ctx); - } - const callback = handler; - return async (_args, ctx) => callback(ctx); -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -/** -* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} -* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that -* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion -* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). -*/ -function convertOutputSchemaJson(outputSchema) { - if (outputSchema === void 0) return void 0; - try { - return standardSchemaToJsonSchema(outputSchema, "output"); - } catch { - return; - } -} -/** -* Creates a type-safe prompt handler that captures the schema and callback in a closure. -* This eliminates the need for type assertions at the call site. -*/ -function createPromptHandler(name, argsSchema, callback) { - if (argsSchema) { - const typedCallback = callback; - return async (args, ctx) => { - const parseResult = await validateStandardSchema(argsSchema, args); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); - return typedCallback(parseResult.data, ctx); - }; - } else { - const typedCallback = callback; - return async (_args, ctx) => { - return typedCallback(ctx); - }; - } -} -function createCompletionResult(suggestions) { - return { completion: { - values: suggestions.map(String).slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } }; -} -const EMPTY_COMPLETION_RESULT = { completion: { - values: [], - hasMore: false -} }; -/** @internal Gets the shape of a Zod object schema */ -function getSchemaShape(schema) { - const candidate = schema; - if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; -} -/** @internal Checks if a Zod schema is optional */ -function isOptionalSchema(schema) { - return schema?.type === "optional"; -} -/** @internal Unwraps an optional Zod schema */ -function unwrapOptionalSchema(schema) { - if (!isOptionalSchema(schema)) return schema; - return schema.def?.innerType ?? schema; -} - -//#endregion - -//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map - - - - -//#region src/server/perRequestTransport.ts -/** -* The per-request micro-transport: a real, connected `Transport` whose whole -* lifetime is one HTTP exchange. See the module documentation for the -* response shapes it produces. -*/ -var PerRequestHTTPServerTransport = class { - onclose; - onerror; - onmessage; - _classification; - _responseMode; - _started = false; - _used = false; - _closed = false; - _terminalDelivered = false; - /** - * `true` only while the inbound message is being delivered synchronously - * to the connected protocol layer. The pre-handler gates (the era - * registry gate, the edge→instance handoff check, the missing-handler - * rejection) answer inside this window; request handlers always run - * after it (the protocol layer defers them to a microtask). An error - * sent inside the window is therefore ladder-originated, and an error - * sent after it is handler-produced. - */ - _dispatchWindowOpen = false; - _requestId; - _deferredResponse; - _sse; - _abortCleanup; - _keepAliveMs; - constructor(options) { - this._classification = options.classification; - this._responseMode = options.responseMode ?? "auto"; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - async start() { - if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); - this._started = true; - } - /** - * Serves the single exchange: delivers the classified message to the - * connected server instance and resolves with the HTTP response. - * - * Throws when called a second time (the transport is strictly - * single-use), or before a server has been connected to the transport. - * The returned promise rejects with a connection-closed error when the - * transport is closed before a response was produced (for example because - * the client disconnected). - */ - async handleMessage(message, extra) { - if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); - if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); - if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); - this._used = true; - const signal = extra?.request?.signal; - if (signal?.aborted) { - await this.close(); - throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); - } - const messageExtra = { - classification: this._classification, - ...extra?.request !== void 0 && { request: extra.request }, - ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } - }; - if (isJSONRPCRequest(message)) { - this._requestId = message.id; - let resolve; - let reject; - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve; - reject = promiseReject; - }); - this._deferredResponse = { - promise, - resolve, - reject, - settled: false - }; - if (signal !== void 0) { - const onAbort = () => void this.close(); - signal.addEventListener("abort", onAbort, { once: true }); - this._abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - this._dispatchWindowOpen = true; - try { - this.onmessage(message, messageExtra); - } finally { - this._dispatchWindowOpen = false; - } - if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); - return promise; - } - this.onmessage(message, messageExtra); - return new Response(null, { status: 202 }); - } - async send(message, options) { - if (this._closed) return; - const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); - const relatedId = isResponse ? message.id : options?.relatedRequestId; - if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { - if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); - return; - } - if (isResponse) { - if (this._terminalDelivered) return; - this._terminalDelivered = true; - const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; - const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; - if (ladderStatus !== void 0 && this._sse === void 0) { - this.settleResponse(Response.json(message, { - status: ladderStatus, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._sse !== void 0 || this._responseMode === "sse") { - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - this.finalizeStream(); - return; - } - this.settleResponse(Response.json(message, { - status: 200, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._responseMode === "json") return; - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - } - /** - * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the - * exchange is not currently streaming. - */ - writeCommentFrame(comment) { - if (this._closed || this._sse === void 0 || this._sse.closed) return; - const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); - this.writeFrame(`${frame}\n\n`); - } - async close() { - if (this._closed) return; - this._closed = true; - this._abortCleanup?.(); - this._abortCleanup = void 0; - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { - this._deferredResponse.settled = true; - this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); - } - this.onclose?.(); - } - settleResponse(response) { - if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; - this._deferredResponse.settled = true; - this._deferredResponse.resolve(response); - } - upgradeToSse() { - let controller; - const readable = new ReadableStream({ - start: (streamController) => { - controller = streamController; - }, - cancel: () => { - this.close(); - } - }); - this._sse = { - controller, - encoder: new TextEncoder(), - closed: false - }; - this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); - this.settleResponse(new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - })); - } - finalizeStream() { - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - queueMicrotask(() => void this.close()); - } - writeMessageFrame(message) { - this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - writeFrame(frame) { - if (this._sse === void 0 || this._sse.closed) return; - try { - this._sse.controller.enqueue(this._sse.encoder.encode(frame)); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); - } - } -}; - -//#endregion -//#region src/server/invoke.ts -/** -* Serves one classified inbound message on the given server instance and -* returns the HTTP response for the exchange. -* -* The instance is connected to a fresh single-exchange transport, the message -* is injected through the normal transport message path, and whatever the -* dispatch layer produces (the handler result, a protocol-level rejection, or -* streamed related messages followed by the result) is captured as the -* returned `Response`. For request exchanges, teardown rides the transport's -* close chain once the terminal response has been delivered; notification -* exchanges resolve with the 202 response immediately and do NOT run the -* close chain — the transport stays connected until the caller closes it or -* drops the per-request instance, which is the caller's choice either way. -*/ -async function invoke(server, message, ctx) { - const transport = new PerRequestHTTPServerTransport({ - classification: ctx.classification, - ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, - ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } - }); - await server.connect(transport); - return transport.handleMessage(message, { - ...ctx.request !== void 0 && { request: ctx.request }, - ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } - }); -} - -//#endregion -//#region src/server/streamableHttp.ts -/** -* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification -* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). -* -* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. -* -* In stateful mode: -* - Session ID is generated and included in response headers -* - Session ID is always included in initialization responses -* - Requests with invalid session IDs are rejected with `404 Not Found` -* - Non-initialization requests without a session ID are rejected with `400 Bad Request` -* - State is maintained in-memory (connections, message history) -* -* In stateless mode: -* - No Session ID is included in any responses -* - No session validation is performed -* -* @example Stateful setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: () => crypto.randomUUID() -* }); -* -* await server.connect(transport); -* ``` -* -* @example Stateless setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: undefined -* }); -* ``` -* -* @example Hono.js -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" -* app.all('/mcp', async c => { -* return transport.handleRequest(c.req.raw); -* }); -* ``` -* -* @example Cloudflare Workers -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" -* const worker = { -* async fetch(request: Request): Promise { -* return transport.handleRequest(request); -* } -* }; -* ``` -*/ -var WebStandardStreamableHTTPServerTransport = class { - sessionIdGenerator; - _started = false; - _closed = false; - _streamMapping = /* @__PURE__ */ new Map(); - _requestToStreamMapping = /* @__PURE__ */ new Map(); - _requestResponseMap = /* @__PURE__ */ new Map(); - _initialized = false; - _enableJsonResponse = false; - _standaloneSseStreamId = "_GET_stream"; - _eventStore; - _onsessioninitialized; - _onsessionclosed; - _allowedHosts; - _allowedOrigins; - _enableDnsRebindingProtection; - _retryInterval; - _supportedProtocolVersions; - _keepAliveMs; - sessionId; - onclose; - onerror; - onmessage; - constructor(options = {}) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - this._retryInterval = options.retryInterval; - this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - startKeepAlive(controller, encoder) { - if (this._closed) return void 0; - const timer = armSseKeepAlive(this._keepAliveMs, () => { - try { - controller.enqueue(encoder.encode(": keepalive\n\n")); - } catch { - if (timer !== void 0) clearInterval(timer); - } - }); - return timer; - } - /** - * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) throw new Error("Transport already started"); - this._started = true; - } - /** - * Sets the supported protocol versions for header validation. - * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. - */ - setSupportedProtocolVersions(versions) { - this._supportedProtocolVersions = versions; - } - /** - * Helper to create a JSON error response - */ - createJsonErrorResponse(status, code, message, options) { - const error = { - code, - message - }; - if (options?.data !== void 0) error.data = options.data; - return Response.json({ - jsonrpc: "2.0", - error, - id: null - }, { - status, - headers: { - "Content-Type": "application/json", - ...options?.headers - } - }); - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error response if validation fails, `undefined` if validation passes. - */ - validateRequestHeaders(req) { - if (!this._enableDnsRebindingProtection) return; - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.get("host"); - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - const error = `Invalid Host header: ${hostHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.get("origin"); - if (originHeader && !this._allowedOrigins.includes(originHeader)) { - const error = `Invalid Origin header: ${originHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - } - /** - * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` - * Returns a `Response` object (Web Standard) - */ - async handleRequest(req, options) { - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const validationError = this.validateRequestHeaders(req); - if (validationError) return validationError; - switch (req.method) { - case "POST": return this.handlePostRequest(req, options); - case "GET": return this.handleGetRequest(req); - case "DELETE": return this.handleDeleteRequest(req); - default: return this.handleUnsupportedRequest(); - } - } - /** - * Returns true if the client's protocol version supports empty SSE data in - * priming events (the fix shipped with protocol version `2025-11-25`). - * - * The version is checked for membership in this transport instance's - * supported protocol versions rather than with an open-ended - * `>= '2025-11-25'` comparison: the value may come from an `initialize` - * request body, which (unlike the `MCP-Protocol-Version` header) is not - * validated against `supportedProtocolVersions` before reaching this - * check. An unknown future version string must not silently enable - * behavior reserved for versions this transport actually supports. - */ - supportsEmptySSEData(protocolVersion) { - return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; - } - /** - * Writes a priming event to establish resumption capability. - * Only sends if `eventStore` is configured (opt-in for resumability) and - * the client's protocol version supports empty SSE data (a supported - * version that is >= `2025-11-25`). - */ - async writePrimingEvent(controller, encoder, streamId, protocolVersion) { - if (!this._eventStore) return; - if (!this.supportsEmptySSEData(protocolVersion)) return; - const primingEventId = await this._eventStore.storeEvent(streamId, {}); - let primingEvent = `id: ${primingEventId}\ndata: \n\n`; - if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; - controller.enqueue(encoder.encode(primingEvent)); - } - /** - * Handles `GET` requests for SSE stream - */ - async handleGetRequest(req) { - if (!req.headers.get("accept")?.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); - } - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - if (this._eventStore) { - const lastEventId = req.headers.get("last-event-id"); - if (lastEventId) return this.replayEvents(lastEventId); - } - if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); - } - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - this._streamMapping.set(this._standaloneSseStreamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(this._standaloneSseStreamId); - try { - streamController.close(); - } catch {} - } - }); - keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId) { - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); - return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); - } - try { - let streamId; - if (this._eventStore.getStreamIdForEventId) { - streamId = await this._eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); - return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); - } - if (this._streamMapping.get(streamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); - } - } - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - let cancelled = false; - let replayedStreamId; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - cancelled = true; - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); - } - }); - const replayedEventIds = /* @__PURE__ */ new Set(); - replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { - replayedEventIds.add(eventId); - if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { - streamController.close(); - } catch {} - } }); - if (this._closed || cancelled) { - try { - streamController.close(); - } catch {} - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - this._streamMapping.get(replayedStreamId)?.cleanup(); - this._streamMapping.set(replayedStreamId, { - controller: streamController, - encoder, - replayedEventIds, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - }); - if (replayedStreamId !== this._standaloneSseStreamId) { - if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - } - if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); - } - } - /** - * Writes an event to an SSE stream via controller with proper formatting - */ - writeSSEEvent(controller, encoder, message, eventId) { - try { - let eventData = `event: message\n`; - if (eventId) eventData += `id: ${eventId}\n`; - eventData += `data: ${JSON.stringify(message)}\n\n`; - controller.enqueue(encoder.encode(eventData)); - return true; - } catch (error) { - this.onerror?.(error); - return false; - } - } - /** - * Handles unsupported requests (`PUT`, `PATCH`, etc.) - */ - handleUnsupportedRequest() { - this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: "Method not allowed." - }, - id: null - }, { - status: 405, - headers: { - Allow: "GET, POST, DELETE", - "Content-Type": "application/json" - } - }); - } - /** - * Handles `POST` requests containing JSON-RPC messages - */ - async handlePostRequest(req, options) { - try { - const acceptHeader = req.headers.get("accept"); - if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); - } - if (!isJsonContentType(req.headers.get("content-type"))) { - this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const request = req; - let rawMessage; - if (options?.parsedBody === void 0) try { - rawMessage = await req.json(); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); - } - else rawMessage = options.parsedBody; - let messages; - try { - messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); - if (isInitializationRequest) { - if (this._initialized && this.sessionId !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); - } - if (messages.length > 1) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - if (!isInitializationRequest) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - if (!messages.some((element) => isJSONRPCRequest(element))) { - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - return new Response(null, { status: 202 }); - } - const streamId = crypto.randomUUID(); - const initRequest = messages.find((m) => isInitializeRequest(m)); - const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (this._enableJsonResponse) return new Promise((resolve) => { - this._streamMapping.set(streamId, { - resolveJson: resolve, - cleanup: () => { - this._streamMapping.delete(streamId); - } - }); - for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - }); - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - for (const message of messages) if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(streamId); - try { - streamController.close(); - } catch {} - } - }); - this._requestToStreamMapping.set(message.id, streamId); - } - await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); - for (const message of messages) { - let closeSSEStream; - let closeStandaloneSSEStream; - if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { - closeSSEStream = () => { - this.closeSSEStream(message.id); - }; - closeStandaloneSSEStream = () => { - this.closeStandaloneSSEStream(); - }; - } - this.onmessage?.(message, { - authInfo: options?.authInfo, - request, - closeSSEStream, - closeStandaloneSSEStream - }); - } - if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { - status: 200, - headers - }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); - } - } - /** - * Handles `DELETE` requests to terminate sessions - */ - async handleDeleteRequest(req) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - try { - await Promise.resolve(this._onsessionclosed?.(this.sessionId)); - return new Response(null, { status: 200 }); - } finally { - await this.close(); - } - } - /** - * Validates session ID for non-initialization requests. - * Returns `Response` error if invalid, `undefined` otherwise - */ - validateSession(req) { - if (this.sessionIdGenerator === void 0) return; - if (!this._initialized) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); - } - const sessionId = req.headers.get("mcp-session-id"); - if (!sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); - } - if (sessionId !== this.sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Session not found")); - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - } - /** - * Validates the `MCP-Protocol-Version` header on incoming requests. - * - * For initialization: Version negotiation handles unknown versions gracefully - * (server responds with its supported version). - * - * For subsequent requests with `MCP-Protocol-Version` header: - * - Accept if in supported list - * - 400 if unsupported - * - * For HTTP requests without the `MCP-Protocol-Version` header: - * - Accept and default to the version negotiated at initialization - */ - validateProtocolVersion(req) { - const protocolVersion = req.headers.get("mcp-protocol-version"); - if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { - const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(400, -32e3, error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - for (const { cleanup } of this._streamMapping.values()) cleanup(); - this._streamMapping.clear(); - this._requestResponseMap.clear(); - this.onclose?.(); - } - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId) { - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) return; - const stream = this._streamMapping.get(streamId); - if (stream) stream.cleanup(); - } - /** - * Close the standalone `GET` SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream() { - const stream = this._streamMapping.get(this._standaloneSseStreamId); - if (stream) stream.cleanup(); - } - async send(message, options) { - let requestId = options?.relatedRequestId; - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; - if (requestId === void 0) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); - let eventId; - if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === void 0) return; - if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); - return; - } - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); - let stream = this._streamMapping.get(streamId); - if (!this._enableJsonResponse) { - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - stream = this._streamMapping.get(streamId); - } - if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); - } - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); - if (relatedIds.every((id) => this._requestResponseMap.has(id))) { - if (!stream) { - if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - if (this._enableJsonResponse && stream.resolveJson) { - const headers = { "Content-Type": "application/json" }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); - if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { - status: 200, - headers - })); - else stream.resolveJson(Response.json(responses, { - status: 200, - headers - })); - stream.cleanup(); - } else stream.cleanup(); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -}; - -//#endregion -//#region src/server/createMcpHandler.ts -/** -* The JSON-RPC id to echo on an entry-built error response: the body's `id` -* when the body is a single JSON-RPC request whose id is a string or number, -* `null` otherwise. Error responses must carry the id of the request they -* correspond to whenever it could be read; `null` is reserved for the cases -* where no single request id is determinable — unparseable bodies, body-less -* methods, notifications, posted responses and batch arrays. -*/ -function echoableRequestId(body) { - if (body === null || typeof body !== "object" || Array.isArray(body)) return null; - const { method, id } = body; - if (typeof method !== "string") return null; - return typeof id === "string" || typeof id === "number" ? id : null; -} -function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message, - ...data !== void 0 && { data } - }, - id - }, { status: httpStatus }); -} -function rejectionResponse(rejection, id = null) { - return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); -} -function toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} -function internalServerErrorResponse(id = null) { - return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); -} -/** -* The entry's default legacy serving (`legacy: 'stateless'`): per-request -* stateless serving of 2025-era traffic using the same factory as the modern -* path. Exported as a standalone building block for hand-wired compositions -* (for example mounting legacy stateless serving on its own route next to a -* strict modern endpoint). -* -* Each POST is served by a fresh instance from the factory connected to a -* fresh streamable HTTP transport constructed with only -* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. -* Because serving is per-request and stateless, GET and DELETE (2025 session -* operations) are answered with `405` / `Method not allowed.`, exactly like the -* canonical stateless example. -* -* The optional `onerror` callback receives factory and serving failures on -* this leg (reporting only — the response stays the 500 internal-error body). -* The entry passes its own `onerror` here when expanding the default, so -* legacy-leg failures are never silently swallowed. -*/ -function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { - return async (request, options) => { - if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); - try { - const product = await factory({ - era: "legacy", - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - requestInfo: request - }); - const transport = new WebStandardStreamableHTTPServerTransport({ - sessionIdGenerator: void 0, - ...keepAliveMs !== void 0 && { keepAliveMs } - }); - await product.connect(transport); - const teardown = () => { - transport.close().catch(() => {}); - product.close().catch(() => {}); - }; - request.signal?.addEventListener("abort", teardown, { once: true }); - const response = await transport.handleRequest(request, { - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } - }); - if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { - teardown(); - return response; - } - const reader = response.body.getReader(); - let toreDown = false; - const completeExchange = () => { - if (!toreDown) { - toreDown = true; - teardown(); - } - }; - const monitoredBody = new ReadableStream({ - pull: async (controller) => { - try { - const { done, value } = await reader.read(); - if (done) { - completeExchange(); - controller.close(); - return; - } - if (value !== void 0) controller.enqueue(value); - } catch (error) { - completeExchange(); - controller.error(error); - } - }, - cancel: (reason) => { - completeExchange(); - return reader.cancel(reason).catch(() => {}); - } - }); - return new Response(monitoredBody, { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } catch (error) { - try { - onerror?.(toError(error)); - } catch {} - return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); - } - }; -} -function legacyStatelessFallback(factory, onerror) { - return createLegacyStatelessFallback(factory, onerror); -} -/** -* The entry's classification step: read the request body exactly once (unless -* a pre-parsed body is supplied) and classify the request with -* {@linkcode classifyInboundRequest}. This is the single code path behind both -* {@linkcode createMcpHandler}'s routing and the exported -* {@linkcode isLegacyRequest} predicate, so the two can never disagree. -* -* Pass `needsForward: false` when the caller never reads `forwardRequest` — -* the body-preserving clone is then skipped and `forwardRequest` is the -* (consumed) input request. -*/ -async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { - const httpMethod = request.method.toUpperCase(); - let body; - let parsedBody = providedParsedBody; - let forwardRequest = request; - let unparseable = false; - if (httpMethod === "POST") { - if (parsedBody === void 0) { - if (needsForward) forwardRequest = request.clone(); - let bodyText; - try { - bodyText = await request.text(); - } catch { - return { step: "unreadable-body" }; - } - try { - body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); - } catch { - unparseable = true; - } - if (!unparseable && body !== void 0) parsedBody = body; - } else body = parsedBody; - if (unparseable || body === void 0) return { - step: "no-json-body", - forwardRequest - }; - } - return { - step: "classified", - outcome: classifyInboundRequest({ - httpMethod, - protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0, - ...body !== void 0 && { body } - }), - body, - parsedBody, - forwardRequest - }; -} -/** -* Whether {@linkcode createMcpHandler} would route this request to its legacy -* (2025-era) serving rather than the modern (2026-07-28) path. -* -* Call it with just the request: `await isLegacyRequest(request)`. For a -* `POST` the body is read from an internal clone, so the request you pass -* stays fully readable for whichever handler you route it to — no second -* argument is needed. (In a Node `(req, res)` handler, build that `Request` -* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body -* parser, which has already drained the Node stream, build it as -* `toWebRequest(req, req.body)` so the bytes come from the parsed body — -* either way the predicate still takes just the request.) The optional -* `parsedBody` is a perf escape hatch for a body you already hold parsed: -* pass it and the predicate classifies from the value directly, reading and -* cloning nothing. It is needed, not just faster, when the request's own -* body was already read — the internal clone is then impossible (cloning a -* used body throws a `TypeError`), so such a single-argument call rejects -* instead of guessing. -* -* This is the entry's own classification step exported as a predicate — it -* runs exactly the code `createMcpHandler` runs to make the routing decision, -* not a re-implementation — so a hand-wired composition that branches on it -* can never disagree with the entry. It is classification only: hand-wired -* compositions must validate Content-Type themselves (415 for POSTs whose -* media type is not `application/json`, via {@linkcode isJsonContentType}) -* before dispatching either leg — routing the legacy leg into the SDK -* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy -* deployment (for example a sessionful streamable HTTP wiring) serving 2025 -* traffic next to a strict modern endpoint, now that the entry has no -* handler-valued `legacy` option: -* -* ```ts -* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; -* -* const modern = createMcpHandler(factory, { legacy: 'reject' }); -* -* export default { -* async fetch(request: Request): Promise { -* if (await isLegacyRequest(request)) { -* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring -* return myExistingLegacyHandler(request); -* } -* return modern.fetch(request); -* } -* }; -* ``` -* -* Semantics (identical to the entry's routing): -* -* - Returns `true` only for requests with no per-request `_meta` envelope -* claim: claim-less POSTs (including the `initialize` handshake and 2025-era -* notification POSTs without a modern protocol-version header), body-less -* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted -* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. -* - Returns `false` for everything the modern path answers, including its -* validation-ladder rejections: a request carrying the envelope claim (even -* one naming a revision the endpoint does not serve — the modern path -* answers it with the unsupported-protocol-version error), a malformed -* envelope behind a present claim (answered `-32602`), a request whose -* `MCP-Protocol-Version` header names a modern revision but that lacks the -* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers -* routing on the predicate must send `false` traffic to the modern handler, -* never to a legacy handler — the modern path owns those error answers. -* - `server/discover` probes sent by negotiating clients always carry the -* envelope claim, so they are never legacy; a hand-built claim-less POST to -* a method named `server/discover` has no claim and classifies legacy, -* exactly as the entry itself routes it. -*/ -async function isLegacyRequest(request, parsedBody) { - const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); - return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; -} -/** -* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a -* per-request server factory and, by default, falls back to old-school -* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a -* modern-only strict endpoint. -* -* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, -* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap -* the handler once with `toNodeHandler(handler)` from -* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, -* put Origin/Host validation in front of the handler — the entry itself is -* deliberately validation-free: -* -* ```ts -* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; -* -* export default { -* async fetch(request: Request): Promise { -* const rejected = -* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? -* originValidationResponse(request, localhostAllowedOrigins()); -* return rejected ?? handler.fetch(request); -* } -* }; -* ``` -* -* Use ONE factory for both legs: the same tools/resources/prompts definition -* backs the modern path and the stateless legacy fallback, so the two eras can -* never drift apart. To keep an existing legacy deployment (for example a -* sessionful streamable HTTP wiring) serving 2025 traffic instead of the -* stateless fallback, route in user land with {@linkcode isLegacyRequest} in -* front of a strict handler — see that predicate's documentation for the -* pattern. Power users composing transport-neutral routing can also use the -* exported building blocks directly: {@linkcode classifyInboundRequest} for -* the era decision and `PerRequestHTTPServerTransport` for single-exchange -* serving — such compositions must reject POSTs whose Content-Type media type -* is not `application/json` (415) before parsing the body, using -* {@linkcode isJsonContentType}; neither building block performs this -* validation itself. -* -* The entry performs no token verification: `authInfo` given to `fetch` is -* passed through to handlers and the factory as-is and is never derived from -* request headers. -*/ -function createMcpHandler(factory, options = {}) { - const { legacy, onerror, responseMode } = options; - if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); - /** Modern per-request instances with an exchange still in flight (close() tears these down). */ - const inflight = /* @__PURE__ */ new Set(); - let closed = false; - const reportError = (error) => { - try { - onerror?.(error); - } catch {} - }; - const bus = options.bus ?? new InMemoryServerEventBus(reportError); - const notify = createServerNotifier(bus); - const listenRouter = createListenRouter({ - bus, - maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, - keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, - onerror: reportError - }); - if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); - const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); - async function serveModern(route, request, authInfo) { - const claimedRevision = route.classification.revision; - if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedRevision ?? "unknown" - }); - reportError(error); - return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); - } - const stdHeaderRejection = validateStandardRequestHeaders({ - httpMethod: request.method, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0 - }, route); - if (stdHeaderRejection !== void 0) { - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); - return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); - } - const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; - const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; - if (route.messageKind === "request") { - const required = requiredClientCapabilitiesForRequest(route.message.method); - if (required !== void 0) { - const missing = missingClientCapabilities(required, declaredClientCapabilities); - if (missing !== void 0) { - const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); - reportError(error); - return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); - } - } - } - const product = await factory({ - era: "modern", - ...authInfo !== void 0 && { authInfo }, - requestInfo: request - }); - const server = product instanceof McpServer ? product.server : product; - if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { - const capabilities = server.getCapabilities(); - const serverInfo = serverIdentityOf(server); - product.close().catch(reportError); - return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); - } - if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { - const callParams = route.message.params; - const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; - const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); - if (inputSchema !== void 0) { - const scan = scanXMcpHeaderDeclarations(inputSchema); - if (scan.valid && scan.declarations.length > 0) { - const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); - if (rejection !== void 0) { - product.close().catch(reportError); - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); - return rejectionResponse(rejection, route.message.id); - } - } - } - } - setNegotiatedProtocolVersion(server, claimedRevision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (meta !== void 0) seedClientIdentityFromEnvelope(server, { - clientInfo: meta[CLIENT_INFO_META_KEY], - clientCapabilities: declaredClientCapabilities - }); - const previousOnClose = server.onclose; - inflight.add(server); - server.onclose = () => { - inflight.delete(server); - previousOnClose?.(); - }; - try { - const response = await invoke(product, route.message, { - classification: route.classification, - request, - ...authInfo !== void 0 && { authInfo }, - ...responseMode !== void 0 && { responseMode }, - ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } - }); - if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); - return response; - } catch (error) { - if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); - await server.close().catch(() => {}); - inflight.delete(server); - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(route.message)); - } - } - async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { - if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { - ...authInfo !== void 0 && { authInfo }, - ...parsedBody !== void 0 && { parsedBody } - }); - const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (strict === void 0) return new Response(null, { status: 202 }); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); - return rejectionResponse(strict, echoableRequestId(parsedBody)); - } - async function handle(request, requestOptions) { - const authInfo = requestOptions?.authInfo; - if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { - reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); - if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); - if (classified.step === "no-json-body") { - if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); - return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); - } - const { outcome, body, parsedBody, forwardRequest } = classified; - try { - switch (outcome.kind) { - case "reject": - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); - return rejectionResponse(outcome, echoableRequestId(body)); - case "modern": return await serveModern(outcome, request, authInfo); - case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); - } - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(body)); - } - } - const fetchFace = async (request, requestOptions) => { - if (closed) throw new Error("This MCP handler has been closed"); - try { - return await handle(request, requestOptions); - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); - } - }; - return { - fetch: fetchFace, - notify, - bus, - close: async () => { - closed = true; - listenRouter.closeAll(); - const closing = [...inflight].map((server) => server.close().catch(() => {})); - inflight.clear(); - await Promise.all(closing); - } - }; -} - -//#endregion -//#region src/server/middleware/bearerAuth.ts -function headerQuotedValue(value) { - return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); -} -function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { - let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; - if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; - if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; - return header; -} -/** -* Validate a raw `Authorization` header value as a Bearer token and return -* the verified {@link AuthInfo}. -* -* The runtime-neutral core of Bearer authentication: it parses the header, -* runs the verifier, enforces `requiredScopes`, and rejects tokens without an -* expiration or past it. On any failure it throws an {@link OAuthError} — -* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP -* answer, or use {@link requireBearerAuth} to get both steps as one call. -* -* Framework adapters build on this: `requireBearerAuth` from -* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. -*/ -async function verifyBearerToken(authorizationHeader, options) { - const { verifier, requiredScopes = [] } = options; - if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); - const [type, token] = authorizationHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); - const authInfo = await verifier.verifyAccessToken(token); - if (requiredScopes.length > 0) { - if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); - } - if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); - else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); - return authInfo; -} -/** -* Build the HTTP answer for a Bearer authentication failure. -* -* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and -* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` -* challenge, with `resource_metadata` when configured so clients can discover -* the Authorization Server), `500` for `server_error`, `400` for anything -* else. A non-`OAuthError` value answers `500 server_error`. The body is the -* OAuth error JSON. -*/ -function bearerAuthChallengeResponse(error, options) { - const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; - if (!(error instanceof OAuthError)) { - const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); - return Response.json(serverError.toResponseObject(), { status: 500 }); - } - switch (error.code) { - case OAuthErrorCode.InvalidToken: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 401, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.InsufficientScope: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 403, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); - default: return Response.json(error.toResponseObject(), { status: 400 }); - } -} -/** -* Require a valid Bearer token on web-standard requests. -* -* The framework-free counterpart of `requireBearerAuth` from -* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a -* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The -* returned gate resolves to the verified {@link AuthInfo}, or to the -* ready-to-return challenge `Response` when the request must be refused. -* -* @example -* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" -* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); -* -* async function fetchHandler(request: Request): Promise { -* const auth: AuthInfo | Response = await gate(request); -* if (auth instanceof Response) return auth; -* return handler.fetch(request, { authInfo: auth }); -* } -* ``` -*/ -function requireBearerAuth(options) { - const { verifier, requiredScopes = [], resourceMetadataUrl } = options; - const resolved = { - verifier, - requiredScopes, - resourceMetadataUrl - }; - return async (request) => { - const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); - try { - return await verifyBearerToken(authorizationHeader || void 0, resolved); - } catch (error) { - return bearerAuthChallengeResponse(error, resolved); - } - }; -} - -//#endregion -//#region src/server/middleware/hostHeaderValidation.ts -/** -* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). -* -* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). -* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). -*/ -function validateHostHeader(hostHeader, allowedHostnames) { - if (!hostHeader) return { - ok: false, - errorCode: "missing_host", - message: "Missing Host header" - }; - let hostname; - try { - hostname = new URL(`http://${hostHeader}`).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_host_header", - message: `Invalid Host header: ${hostHeader}`, - hostHeader - }; - } - if (!allowedHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_host", - message: `Invalid Host: ${hostname}`, - hostHeader, - hostname - }; - return { - ok: true, - hostname - }; -} -/** -* Convenience allowlist for `localhost` DNS rebinding protection. -*/ -function localhostAllowedHostnames() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for DNS rebinding protection. -* @example -* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" -* const result = validateHostHeader(req.headers.get('host'), ['localhost']); -* ``` -*/ -function hostHeaderValidationResponse(req, allowedHostnames) { - const result = validateHostHeader(req.headers.get("host"), allowedHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/middleware/oauthMetadata.ts -function checkIssuerUrl(issuer, allowInsecure) { - if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); - if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); -} -/** -* Derive the RFC 9728 Protected Resource Metadata document from -* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL -* (HTTPS required outside localhost) in the process. -* -* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build -* on this; use it directly when serving the document through your own -* routing — or call it once at startup to fail fast on a misconfigured -* issuer before any request arrives. -*/ -function buildOAuthProtectedResourceMetadata(options) { - checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); - return { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: options.serviceDocumentationUrl?.href - }; -} -/** -* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server -* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. -* -* @example -* ```ts -* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) -* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' -* ``` -*/ -function getOAuthProtectedResourceMetadataUrl(serverUrl) { - return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; -} -/** The RFC 9728 path-aware well-known path for a resource URL. */ -function protectedResourceMetadataPath(resourceServerUrl) { - const rsPath = stripTrailingSlash(resourceServerUrl.pathname); - return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; -} -function stripTrailingSlash(path) { - return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; -} -const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; -function metadataDocumentResponse(request, metadata) { - if (request.method === "OPTIONS") { - const requestedHeaders = request.headers.get("access-control-request-headers"); - return new Response(null, { - status: 204, - headers: { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": ALLOWED_METHODS, - ...requestedHeaders === null ? {} : { - "Access-Control-Allow-Headers": requestedHeaders, - Vary: "Access-Control-Request-Headers" - } - } - }); - } - if (request.method !== "GET" && request.method !== "HEAD") { - const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); - return Response.json(error.toResponseObject(), { - status: 405, - headers: { - Allow: ALLOWED_METHODS, - "Access-Control-Allow-Origin": "*" - } - }); - } - const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); - return request.method === "HEAD" ? new Response(null, { - status: response.status, - headers: response.headers - }) : response; -} -/** -* Serve the two OAuth discovery documents an MCP server acting as a Resource -* Server exposes, from a web-standard `fetch(request)` handler: -* -* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected -* Resource Metadata, derived from the supplied options (path-aware: the -* resource URL's path is reflected in the route). -* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization -* Server Metadata, passed through verbatim. -* -* Returns the matched document `Response` (JSON with permissive CORS, `405` -* with an `Allow` header for non-GET methods, `204` for CORS preflight), or -* `undefined` when the request path is neither well-known route — fall -* through to your own routing. The framework-free counterpart of -* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with -* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so -* unauthenticated clients can discover the AS from the `401` challenge. -* -* @example -* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" -* async function fetchHandler(request: Request): Promise { -* return oauthMetadataResponse(request, options) ?? serveMcp(request); -* } -* ``` -*/ -function oauthMetadataResponse(request, options) { - const requestPath = stripTrailingSlash(new URL(request.url).pathname); - if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); - if (requestPath === "/.well-known/oauth-authorization-server") { - buildOAuthProtectedResourceMetadata(options); - return metadataDocumentResponse(request, options.oauthMetadata); - } -} - -//#endregion -//#region src/server/middleware/originValidation.ts -/** -* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). -* -* - A missing/empty `Origin` header passes: non-browser clients do not send one, -* and only browser-originated requests carry the header this check defends against. -* - Allowlist items are hostnames only (no scheme, no port), the same convention as -* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). -* - Any present value that cannot be parsed as an origin URL — including the literal -* `null` origin browsers send for opaque contexts — is rejected (deny on failure). -*/ -function validateOriginHeader(originHeader, allowedOriginHostnames) { - if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; - let hostname; - try { - hostname = new URL(originHeader).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - } - if (hostname === "") return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - if (!allowedOriginHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_origin", - message: `Invalid Origin: ${hostname}`, - originHeader, - hostname - }; - return { - ok: true, - origin: originHeader, - hostname - }; -} -/** -* Convenience allowlist of localhost-class origin hostnames, mirroring -* `localhostAllowedHostnames`. -*/ -function localhostAllowedOrigins() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC -* error response when the request's `Origin` header is not allowed, and -* `undefined` when the request may proceed. -* -* ```ts -* const rejected = originValidationResponse(request, localhostAllowedOrigins()); -* if (rejected) return rejected; -* ``` -*/ -function originValidationResponse(req, allowedOriginHostnames) { - const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/requestStateCodec.ts -const PREFIX = "v1."; -function bytesToBase64Url(bytes) { - let bin = ""; - for (const b of bytes) bin += String.fromCodePoint(b); - return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); -} -function constantTimeTagEqual(a, b) { - if (a.length !== b.length) return false; - let r = 0; - for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); - return r === 0; -} -function base64UrlToBytes(s) { - const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return bytes; -} -/** -* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` -* (protocol revision 2026-07-28). -* -* `requestState` round-trips through the client and is attacker-controlled -* input on re-entry. The SDK applies no protection of its own; this helper is -* the convenience implementation of the spec's integrity MUST so authors don't -* hand-roll HMAC. Wire shape: -* -* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) -* -* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` -* — the binding value is never embedded raw. -* -* The codec is **signed, not encrypted**: the body is integrity-protected but -* the client can base64url-decode it and read the payload (`p`) in clear. Do -* not put secrets in the payload; use an AEAD construction if confidentiality -* is required. The handler reads its payload back via the typed -* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` -* (integrity proven, payload decoded) by the time the handler is entered. -* -* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for -* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). -* See `examples/mrtr/server.ts` for a worked end-to-end example. -* -* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference -* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and -* derives independent cipher / bind-HMAC sub-keys from the operator secret via -* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is -* supplied. This codec deliberately ships only the signed mode and a single -* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and -* an encrypted mode are intentionally out of scope for the initial release. -*/ -function createRequestStateCodec(options) { - const subtle = globalThis.crypto?.subtle; - if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); - const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); - if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); - const ttlSeconds = options.ttlSeconds ?? 600; - if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); - const bind = options.bind; - let cryptoKey; - const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { - name: "HMAC", - hash: "SHA-256" - }, false, ["sign", "verify"]); - const utf8 = new TextEncoder(); - const BIND_LABEL = "mcp.requestState.bind:"; - const bindTag = async (value) => { - return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); - }; - return { - async mint(payload, ctx) { - const envelope = { - p: payload, - exp: Math.floor(Date.now() / 1e3) + ttlSeconds - }; - if (bind !== void 0) { - if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); - envelope.b = await bindTag(bind(ctx)); - } - const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); - return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; - }, - async verify(state, ctx) { - const dot = state.lastIndexOf("."); - if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); - const body = state.slice(3, dot); - let macBytes; - try { - macBytes = base64UrlToBytes(state.slice(dot + 1)); - } catch { - throw new Error("malformed"); - } - if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); - let envelope; - try { - envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); - } catch { - throw new Error("malformed"); - } - if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); - if (bind !== void 0) { - const expected = await bindTag(bind(ctx)); - if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); - } else if (envelope.b !== void 0) throw new Error("bind"); - return envelope.p; - } - }; -} - -//#endregion -//#region src/fromJsonSchema.ts -let _defaultValidator; -function dist_fromJsonSchema(schema, validator) { - return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); -} - -//#endregion - -//# sourceMappingURL=index.mjs.map -const mcpApps = Object.freeze([]); - -/* export default */ const mcp_status_073c1634_0 = (mcpApps); - -// Generated by agent-bundle. Do not edit. -const meta_name = "mcp-app-example"; -const packageName = "@agent-bundle-example/mcp-app"; -const packageVersion = undefined; -const meta_version = "1.0.0"; -const meta_meta = Object.freeze({ - name: meta_name, - packageName: packageName, - packageVersion: packageVersion, - version: meta_version -}); -/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - - - - -const app = mcp_status_073c1634_0["0"]; -if (app === undefined) throw new Error('Expected the status MCP App.'); -const serviceCatalog = Object.freeze({ - compiler: healthyCompilerStatus, - 'payments-api': Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'P95 latency', - status: 'failing' - }) - ]), - service: 'payments-api', - status: 'degraded', - summary: 'Payment latency is above the release threshold.' - }) -}); -const createStatusServer = ()=>{ - // The compiler stamps this project's identity into `agent-bundle/meta`, so - // the wire identity cannot drift from the config or package.json. - const server = new mcp_DXXb3Vv3_McpServer({ - name: meta_name, - version: (/* inlined export .version */"1.0.0") - }); - server.registerResource(app.name, app.resourceUri, { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - mimeType: app.mimeType - }, async (uri)=>({ - contents: [ - { - mimeType: app.mimeType, - text: app.html, - uri: uri.href - } - ] - })); - server.registerTool('show-status', { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - description: 'Show the health of one example service.', - inputSchema: schemas_object({ - service: schemas_enum([ - 'compiler', - 'payments-api' - ]) - }) - }, async ({ service })=>{ - const result = serviceCatalog[service]; - return { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - content: [ - { - text: result.summary, - type: 'text' - } - ], - structuredContent: result - }; - }); - return server; -}; -/** - * Default-exported server factory: `agent-bundle build` detects it and wraps - * this entry in the framework stdio lifecycle shell (console-to-stderr guard, - * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). - */ /* export default */ const mcp_status = (createStatusServer); - - - - - -//#region src/server/stdio.ts -/** -* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. -* -* This transport is only available in Node.js environments. -* -* @example -* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* const transport = new StdioServerTransport(); -* await server.connect(transport); -* ``` -*/ -var stdio_StdioServerTransport = class { - _readBuffer; - _started = false; - _closed = false; - constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); - } - onclose; - onerror; - onmessage; - _ondata = (chunk) => { - try { - this._readBuffer.append(chunk); - this.processReadBuffer(); - } catch (error) { - this.onerror?.(error); - this.close().catch(() => {}); - } - }; - _onerror = (error) => { - this.onerror?.(error); - }; - _onstdouterror = (error) => { - this.onerror?.(error); - this.close().catch(() => {}); - }; - /** - * Starts listening for messages on `stdin`. - */ - async start() { - if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); - this._stdout.on("error", this._onstdouterror); - } - processReadBuffer() { - while (true) try { - const message = this._readBuffer.readMessage(); - if (message === null) break; - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - this._stdout.off("error", this._onstdouterror); - if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); - return new Promise((resolve, reject) => { - const json = serializeMessage(message); - let settled = false; - const onError = (error) => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - reject(error); - }; - const onDrain = () => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - resolve(); - }; - this._stdout.once("error", onError); - if (this._stdout.write(json)) { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - resolve(); - } else if (!settled) this._stdout.once("drain", onDrain); - }); - } -}; - -//#endregion -//#region src/server/serveStdio.ts -/** -* How long the probe-discard path waits for the probe instance to answer the -* requests it was delivered before closing it. The wait normally settles as -* soon as the DiscoverResult is handed to the wire (or immediately, when a -* delivered cancellation already settled the probe); the bound is a backstop -* so no edge can ever hold the connection's inbound pump indefinitely behind -* the discard. -*/ -const DISCARD_ANSWER_TIMEOUT_MS = 3e3; -/** -* The transport a pinned instance is connected to: a thin channel that writes -* through to the entry-owned wire transport and receives the messages the -* entry forwards. The wire transport itself is never handed to an instance — -* that is what lets the entry discard an optimistic probe instance (close the -* channel) without tearing down the connection. -*/ -var StdioConnectionChannel = class { - onclose; - onerror; - onmessage; - _closed = false; - /** Request ids the entry delivered to the instance that the instance has not yet answered. */ - _pendingRequests = /* @__PURE__ */ new Set(); - _drainWaiters = []; - constructor(_wire, _onInstanceClose, _outboundIntercept) { - this._wire = _wire; - this._onInstanceClose = _onInstanceClose; - this._outboundIntercept = _outboundIntercept; - } - async start() {} - async send(message, options) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - const { id } = message; - if (id !== void 0) this._settle(id); - } - if (this._closed) return; - if (this._outboundIntercept?.(message) === "handled") return; - return this._wire.send(message, options); - } - setProtocolVersion = (version) => { - this._wire.setProtocolVersion?.(version); - }; - /** Forwards one inbound message to the connected instance. */ - deliver(message, extra) { - if (this._closed) return; - if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); - else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0) this._settle(cancelledId); - } - this.onmessage?.(message, extra); - } - /** - * Resolves once every request delivered to the instance has been answered - * through {@linkcode send}, settled by a delivered cancellation, or the - * channel has been closed and nothing further can be answered. The wait is - * bounded by `timeoutMs` as a backstop so no edge can hold the caller - * indefinitely; resolves `false` only when the bound elapsed with requests - * still unanswered. Used by the probe-discard path so a probe request the - * entry accepted is never silently dropped. - */ - async whenRequestsAnswered(timeoutMs) { - if (this._closed || this._pendingRequests.size === 0) return true; - return await new Promise((resolve) => { - const waiter = () => { - clearTimeout(timer); - resolve(true); - }; - const timer = setTimeout(() => { - this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); - resolve(false); - }, timeoutMs); - this._drainWaiters.push(waiter); - }); - } - async close() { - if (this._closed) return; - this._closed = true; - this._pendingRequests.clear(); - this._releaseDrainWaiters(); - try { - this._onInstanceClose(); - } finally { - this.onclose?.(); - } - } - _settle(id) { - this._pendingRequests.delete(id); - if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); - } - _releaseDrainWaiters() { - const waiters = this._drainWaiters; - this._drainWaiters = []; - for (const waiter of waiters) waiter(); - } -}; -/** -* Classifies one message of the opening exchange with the same body-primary -* rules the HTTP entry applies per request: `initialize` is the legacy -* handshake unless it carries a valid modern envelope claim; a present claim -* is validated (never silently ignored); a claim-less message is 2025-era -* traffic. There is no header layer on stdio, so the body is the only signal. -*/ -function classifyOpeningMessage(message) { - const params = message.params; - if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { - const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (!hasEnvelopeClaim(params)) return { - kind: "legacy", - reason: "no-claim" - }; - const meta = requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return { - kind: "invalid-envelope", - issue: firstIssue - }; - const claimedVersion = envelopeClaimVersion(params); - if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { - kind: "unsupported-revision", - requested: claimedVersion ?? "unknown" - }; - return { - kind: "modern", - revision: claimedVersion, - classification: { - era: "modern", - revision: claimedVersion - } - }; -} -/** -* Serves MCP over stdio from a server factory, owning the era decision for -* the connection: the opening exchange selects the era, ONE instance from the -* factory is pinned for the connection lifetime, and everything after passes -* straight through to it. See the module documentation for the opening rules. -* -* ```ts -* import { serveStdio } from '@modelcontextprotocol/server/stdio'; -* -* serveStdio(() => { -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); -* // register tools/resources/prompts once — the same factory serves both eras -* return server; -* }); -* ``` -*/ -function serveStdio(factory, options = {}) { - const legacyMode = options.legacy ?? "serve"; - const wire = options.transport ?? new stdio_StdioServerTransport(); - let state = { phase: "opening" }; - /** Channel currently being discarded (its close must not tear the connection down). */ - let discarding; - let closing = false; - /** - * Whether the connection has been torn down (`handle.close()` or the wire - * closing). The opening arms re-check this after every await: a close can - * race factory construction, and the continuation must neither resurrect - * the connection state nor keep a late-resolved instance around. - */ - const isTornDown = () => closing || state.phase === "closed"; - const reportError = (error) => { - try { - options.onerror?.(error); - } catch {} - }; - const writeErrorResponse = (id, code, message, data) => wire.send({ - jsonrpc: "2.0", - id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }).catch((error) => reportError(stdio_toError(error))); - /** - * Entry-handled `subscriptions/listen` for this connection: holds the - * active subscriptions, serves inbound listen / cancelled-of-listen - * before the pinned instance is consulted, and rewrites the instance's - * outbound change notifications onto the active subscriptions. Only - * consulted on a modern-pinned connection — on a legacy connection - * change notifications pass straight through (the 2025 unsolicited - * delivery model is unchanged). - */ - const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); - /** Outbound intercept installed on a modern instance's channel. */ - const modernOutboundIntercept = (message) => { - if (!isJSONRPCNotification(message)) return void 0; - const routed = listenRouter.routeOutbound(message); - if (routed === "passthrough") return void 0; - for (const stamped of routed) wire.send({ - jsonrpc: "2.0", - ...stamped - }).catch((error) => reportError(stdio_toError(error))); - return "handled"; - }; - /** - * Entry-handled inbound listen routing for a modern-pinned connection. - * Returns `true` when the message was served at the entry and must NOT - * be delivered to the pinned instance. - */ - const tryServeListen = async (message) => { - if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { - const meta = requestMetaOf(message.params); - const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { - key: "_meta", - problem: "the per-request envelope is required on protocol revision 2026-07-28" - }; - const claimedVersion = envelopeClaimVersion(message.params); - let reply; - if (issue !== void 0) reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` - } - }; - else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedVersion ?? "unknown" - }); - reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: error.code, - message: error.message, - data: error.data - } - }; - } else reply = listenRouter.serve(message); - await wire.send("error" in reply ? reply : { - jsonrpc: "2.0", - method: reply.method, - params: reply.params - }).catch((error) => reportError(stdio_toError(error))); - return true; - } - if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; - } - return false; - }; - /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ - const answerLegacyRejection = (request, reason, requestedVersion) => { - const rejection = modernOnlyStrictRejection({ - kind: "legacy", - reason, - ...requestedVersion !== void 0 && { requestedVersion } - }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (rejection === void 0) return Promise.resolve(); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); - return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); - }; - const onInstanceClosed = (channel) => { - if (closing || channel === discarding) return; - closeAll(); - }; - const connectInstance = async (era, revision) => { - const product = await factory({ era }); - const server = product instanceof McpServer ? product.server : product; - if (era === "modern") { - setNegotiatedProtocolVersion(server, revision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); - } - const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); - await product.connect(channel); - return { - product, - channel - }; - }; - /** Closes an instance whose factory resolved only after the connection was torn down. */ - const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); - const discardProbeInstance = async (instance) => { - discarding = instance.channel; - try { - if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); - await instance.product.close(); - } catch (error) { - reportError(stdio_toError(error)); - } finally { - discarding = void 0; - } - }; - const processMessage = async (message) => { - if (state.phase === "closed") return; - if (state.phase === "pinned") { - if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { - await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); - return; - } - if (state.era === "modern" && await tryServeListen(message)) return; - state.instance.channel.deliver(message); - return; - } - if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { - reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); - return; - } - const opening = classifyOpeningMessage(message); - switch (opening.kind) { - case "invalid-envelope": { - const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); - else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); - return; - } - case "unsupported-revision": - if (isJSONRPCRequest(message)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: opening.requested - }); - reportError(error); - await writeErrorResponse(message.id, error.code, error.message, error.data); - } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); - return; - case "modern": - if (isJSONRPCRequest(message) && message.method === "server/discover") { - if (state.phase === "probe") { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "probe", - instance - }; - instance.channel.deliver(message, { classification: opening.classification }); - return; - } - if (state.phase === "probe") { - if (isJSONRPCNotification(message)) { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - state = { - phase: "pinned", - era: "modern", - instance: state.instance - }; - } else { - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "modern", - instance - }; - } - if (await tryServeListen(message)) return; - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - case "legacy": { - if (legacyMode === "reject") { - if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); - return; - } - if (state.phase === "probe") { - await discardProbeInstance(state.instance); - if (isTornDown()) return; - state = { phase: "opening" }; - } - const instance = await connectInstance("legacy"); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "legacy", - instance - }; - state.instance.channel.deliver(message); - return; - } - } - }; - const queue = []; - let pumping = false; - const pump = async () => { - if (pumping) return; - pumping = true; - try { - while (queue.length > 0) { - const message = queue.shift(); - try { - await processMessage(message); - } catch (error) { - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); - reportError(stdio_toError(error)); - } - } - } finally { - pumping = false; - } - }; - const closeAll = async () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); - if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - await wire.close().catch((error) => reportError(stdio_toError(error))); - }; - wire.onmessage = (message) => { - queue.push(message); - pump(); - }; - wire.onerror = (error) => { - reportError(error); - if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); - }; - wire.onclose = () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - }; - const started = wire.start().catch((error) => { - reportError(stdio_toError(error)); - throw error; - }); - started.catch(() => {}); - return { close: async () => { - await started.catch(() => {}); - await closeAll(); - } }; -} -function stdio_toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} - -//#endregion - -//# sourceMappingURL=stdio.mjs.map -const defaultHeartbeatIntervalMs = 300000; -const defaultActivityThrottleMs = 60000; -const defaultShutdownTimeoutMs = 5000; -const defaultHeartbeatName = 'agent-bundle'; -const redirectConsoleToStderr = ()=>{ - const originalStdoutWrite = process.stdout.write.bind(process.stdout); - const stderrConsole = new console.Console({ - stderr: process.stderr, - stdout: process.stderr - }); - const methods = [ - 'debug', - 'dir', - 'error', - 'info', - 'log', - 'trace', - 'warn' - ]; - for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); - process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); - return Object.freeze({ - restoreProtocolStdout: ()=>{ - process.stdout.write = originalStdoutWrite; - } - }); -}; -const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ - const startedAt = Date.now(); - let lastActivityAt = startedAt; - let lastActivityLogAt = 0; - const log = (reason)=>{ - const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); - const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); - writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); - }; - const timer = setInterval(()=>log('interval'), intervalMs); - timer.unref?.(); - return Object.freeze({ - log, - noteActivity: ()=>{ - lastActivityAt = Date.now(); - if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { - lastActivityLogAt = lastActivityAt; - log('activity'); - } - }, - stop: ()=>clearInterval(timer) - }); -}; -const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ - const heartbeat = createHeartbeat({ - ...void 0 === activityThrottleMs ? {} : { - activityThrottleMs - }, - ...void 0 === heartbeatIntervalMs ? {} : { - intervalMs: heartbeatIntervalMs - }, - ...void 0 === serverName ? {} : { - name: serverName - }, - writeLine: heartbeatEnabled ? writeLine : ()=>void 0 - }); - const keepalive = setInterval(()=>void 0, 60000); - keepalive.unref?.(); - let shuttingDown = false; - const shutdown = async (exitCode = 0)=>{ - if (shuttingDown) return; - shuttingDown = true; - signals.off('SIGINT', handleSigint); - signals.off('SIGTERM', handleSigterm); - stdin.off?.('end', handleStdinEnd); - clearInterval(keepalive); - heartbeat.stop(); - await Promise.race([ - Promise.allSettled([ - Promise.resolve().then(()=>transport.close()), - Promise.resolve().then(()=>server.close()) - ]), - new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) - ]); - exit(exitCode); - }; - const handleSigint = ()=>{ - shutdown(130); - }; - const handleSigterm = ()=>{ - shutdown(143); - }; - const handleStdinEnd = ()=>{ - shutdown(0); - }; - signals.on('SIGINT', handleSigint); - signals.on('SIGTERM', handleSigterm); - stdin.once?.('end', handleStdinEnd); - transport.onclose = ()=>{ - shutdown(0); - }; - await server.connect(transport); - const originalOnMessage = transport.onmessage; - transport.onmessage = (message, extra)=>{ - heartbeat.noteActivity(); - originalOnMessage?.(message, extra); - }; - return Object.freeze({ - heartbeat, - shutdown - }); -}; -const runGeneratedStdioMcpEntry = async (options)=>{ - const guard = redirectConsoleToStderr(); - const entry = await options.loadEntry(); - const factory = entry.default; - if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); - const server = await factory(); - const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); - guard.restoreProtocolStdout(); - const transport = new StdioServerTransport(); - return runStdioServer({ - ...options.lifecycle, - server, - serverName: options.serverName, - transport: transport - }); -}; - - - -await runGeneratedStdioMcpEntry({ - loadEntry: ()=>Promise.resolve(status_namespaceObject), - serverName: "status" -}); - -export {}; diff --git a/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs deleted file mode 100644 index a6f274bf6..000000000 --- a/examples/mcp-app/artifact/claude/scripts/check-service-fixture.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - -const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); -/** - * `agent-bundle build` detects the `main` export and generates the process - * envelope (argv, awaiting, numeric-return exit-code adoption) around it. - */ const main = async ()=>{ - try { - const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); - if (!isHealthyCompilerFixture(fixture)) { - throw new Error('compiler fixture must contain the exact healthy compiler status'); - } - process.stdout.write('Compiler fixture is healthy.\n'); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const check_service_fixture_entry_main = main; -if (typeof check_service_fixture_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/mcp-app/src/scripts/check-service-fixture.ts"); -} -const code = await check_service_fixture_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md deleted file mode 100644 index 8f91a79d7..000000000 --- a/examples/mcp-app/artifact/claude/skills/service-readiness/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: service-readiness -description: Reviews service health evidence and records an auditable readiness decision. ---- -# Service readiness - -## When to use - -Use this Skill when a release, incident decision, or service handoff needs a -clear health verdict backed by named checks and current evidence. - -## Required resources - -- Apply [the service status policy](references/status-policy.md) before - classifying a healthy, degraded, or blocked result. -- Deliver the decision with [the readiness report](assets/readiness-report.md). - -## Workflow - -1. Identify the service and collect its current summary and every labelled - check. Record the command, time, result, and evidence source. -2. Classify any failing check with the status policy. A degraded service is not - release-ready until its failing check has an approved mitigation. -3. State the readiness verdict only after confirming availability and the - service-specific release threshold. -4. Complete the report with the status, checks, evidence, owner, and next - action. Do not omit a failing check from the final decision. - -## Final report requirements - -State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the -service summary; list each labelled check and its status; identify the owner -and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md deleted file mode 100644 index 3da5d52ea..000000000 --- a/examples/mcp-app/artifact/claude/skills/service-readiness/assets/readiness-report.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service readiness report - -## Verdict - -State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. - -## Evidence - -Record the collection time, command or artifact, service summary, and source. - -## Checks - -List every labelled check with its observed status and release threshold. - -## Findings and mitigation - -For each non-passing check, record the impact, owner, mitigation, due date, -and the evidence required to clear it. - -## Next action - -Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md deleted file mode 100644 index 7e5766172..000000000 --- a/examples/mcp-app/artifact/claude/skills/service-readiness/references/status-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service status policy - -## Evidence standard - -Readiness evidence must identify the service, collection time, check label, -observed status, and source command or artifact. Missing or stale evidence is -not a passing check. - -## Status classification - -- **Healthy**: every required release check is passing. -- **Degraded**: availability remains sufficient, but a release threshold such - as P95 latency is failing. Record an owner and mitigation before release. -- **Blocked**: availability or a critical safety check is failing. Do not - release until new passing evidence is collected. -- **Needs evidence**: the service or any required check cannot be verified. - -## Release decision - -Issue `ready` only for a healthy service with current evidence. A degraded -service needs an explicit mitigation decision; a blocked service cannot pass; -and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json b/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json deleted file mode 100644 index 37ef3be4a..000000000 --- a/examples/mcp-app/artifact/codex/.agents/plugins/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"interface":{"displayName":"mcp-app-example"},"name":"mcp-app-example-marketplace","plugins":[{"category":"Productivity","name":"mcp-app-example","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json b/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json deleted file mode 100644 index a86a5db3f..000000000 --- a/examples/mcp-app/artifact/codex/.codex-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"mcp-app-example"},"description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","hooks":"./hooks/hooks.json","interface":{"capabilities":["mcp","hooks","skills"],"category":"Productivity","defaultPrompt":["Help me use mcp-app-example."],"developerName":"mcp-app-example","displayName":"mcp-app-example","longDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","shortDescription":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation."},"mcpServers":"./.mcp.json","name":"mcp-app-example","skills":"./skills/","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/codex/.mcp.json b/examples/mcp-app/artifact/codex/.mcp.json deleted file mode 100644 index 8a84f9c2f..000000000 --- a/examples/mcp-app/artifact/codex/.mcp.json +++ /dev/null @@ -1 +0,0 @@ -{"mcpServers":{"status":{"args":["./mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"./","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"./"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/codex/INSTALL.md b/examples/mcp-app/artifact/codex/INSTALL.md deleted file mode 100644 index f93c7ff0b..000000000 --- a/examples/mcp-app/artifact/codex/INSTALL.md +++ /dev/null @@ -1,16 +0,0 @@ -# Install mcp-app-example - -A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Codex - -Codex installs this bundle from its local marketplace snapshot: - -```sh -codex plugin marketplace add ./ -codex plugin add mcp-app-example@mcp-app-example-marketplace -``` diff --git a/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json deleted file mode 100644 index a765aa4b5..000000000 --- a/examples/mcp-app/artifact/codex/assets/evals/fixtures/status/result.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "service": "compiler", - "status": "healthy", - "summary": "Compiler service is ready for release.", - "checks": [ - { "label": "Availability", "status": "passing" }, - { "label": "Build queue", "status": "passing" } - ] -} diff --git a/examples/mcp-app/artifact/codex/hooks/hooks.json b/examples/mcp-app/artifact/codex/hooks/hooks.json deleted file mode 100644 index eb4f61756..000000000 --- a/examples/mcp-app/artifact/codex/hooks/hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":{"SessionStart":[{"hooks":[{"command":"node \"${PLUGIN_ROOT}/hooks/session-start-session-start-7ab7e8a5.mjs\"","type":"command"}]}]}} diff --git a/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs b/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs deleted file mode 100644 index e3a4ce01c..000000000 --- a/examples/mcp-app/artifact/codex/hooks/session-start-session-start-7ab7e8a5.mjs +++ /dev/null @@ -1,254 +0,0 @@ -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/hooks/session-start.ts -var session_start_namespaceObject = {}; -__webpack_require__.r(session_start_namespaceObject); -__webpack_require__.d(session_start_namespaceObject, { - "default": () => (session_start) }); - - -/* export default */ const session_start = ((event)=>({ - additionalContext: [ - `Service readiness session ${event.sessionId ?? 'is active'} from ${event.source ?? 'an unknown source'}.`, - `Use the service-readiness Skill, then run check-service-fixture from ${event.cwd ?? process.cwd()} before release review.`, - 'Use show-status for compiler or payments-api when live service evidence is needed.' - ].join(' '), - outcome: 'continue' - })); - - -const target = "codex"; -const canonicalEvent = "sessionStart"; -const nativeEvent = "SessionStart"; -const isRecord = (value)=>typeof value === "object" && value !== null && !Array.isArray(value); -const defined = (value)=>Object.fromEntries(Object.entries(value).filter(([, item])=>item !== undefined)); -const decodeCodexNative = (nativeInput)=>({ - agentId: nativeInput.agent_id, - agentTranscriptPath: nativeInput.agent_transcript_path, - agentType: nativeInput.agent_type, - cwd: nativeInput.cwd, - effort: nativeInput.effort, - hookEventName: nativeInput.hook_event_name, - lastAssistantMessage: nativeInput.last_assistant_message, - model: nativeInput.model, - permissionMode: nativeInput.permission_mode, - promptId: nativeInput.prompt_id, - sessionId: nativeInput.session_id, - source: nativeInput.source, - stopHookActive: nativeInput.stop_hook_active, - toolInput: nativeInput.tool_input, - toolName: nativeInput.tool_name, - toolResponse: nativeInput.tool_response, - toolUseId: nativeInput.tool_use_id, - transcriptPath: nativeInput.transcript_path, - turnId: nativeInput.turn_id - }); -const encodeCodexNative = (canonicalInput)=>defined({ - hook_event_name: nativeEvent, - agent_id: canonicalInput.agentId, - agent_transcript_path: canonicalInput.agentTranscriptPath, - agent_type: canonicalInput.agentType, - cwd: canonicalInput.cwd, - effort: canonicalInput.effort, - last_assistant_message: canonicalInput.lastAssistantMessage, - model: canonicalInput.model, - permission_mode: canonicalInput.permissionMode, - prompt_id: canonicalInput.promptId, - session_id: canonicalInput.sessionId, - source: canonicalInput.source, - stop_hook_active: canonicalInput.stopHookActive, - tool_input: canonicalInput.toolInput, - tool_name: canonicalInput.toolName, - tool_response: canonicalInput.toolResponse, - tool_use_id: canonicalInput.toolUseId, - transcript_path: canonicalInput.transcriptPath, - turn_id: canonicalInput.turnId - }); -const decodeNative = decodeCodexNative; -const encodeNative = encodeCodexNative; -const fail = (message)=>{ - throw new Error(`Agent Bundle hook error: ${message}`); -}; -const validateResult = (result)=>{ - if (result === undefined) return undefined; - if (!isRecord(result)) fail("handler must return void or a result object"); - const allowed = new Set([ - "outcome", - "reason", - "updatedInput", - "additionalContext" - ]); - for (const key of Object.keys(result))if (!allowed.has(key)) fail(`handler result has unsupported field ${key}`); - if (result.outcome !== undefined && ![ - "continue", - "deny", - "stop" - ].includes(result.outcome)) fail("handler result outcome is invalid"); - if (result.reason !== undefined && typeof result.reason !== "string") fail("handler result reason must be a string"); - if (result.additionalContext !== undefined && typeof result.additionalContext !== "string") fail("handler result additionalContext must be a string"); - if (result.updatedInput !== undefined && !isRecord(result.updatedInput)) fail("handler result updatedInput must be an object"); - const supportsDeniedReason = canonicalEvent === "beforeTool" || canonicalEvent === "stop" || canonicalEvent === "agentStop"; - if (result.reason !== undefined && !(result.outcome === "deny" && supportsDeniedReason)) fail("reason is only valid for a denied beforeTool, stop, or agentStop hook"); - if (result.outcome === "deny" && supportsDeniedReason && (typeof result.reason !== "string" || result.reason.trim().length === 0)) fail(`denied ${canonicalEvent} hook requires a nonempty reason`); - if ((canonicalEvent === "sessionStart" || canonicalEvent === "afterTool" || canonicalEvent === "agentStart") && (result.outcome === "deny" || result.outcome === "stop" || result.updatedInput !== undefined)) fail(`${canonicalEvent} cannot deny, stop, or replace input`); - if (canonicalEvent === "beforeTool" && (result.outcome === "stop" || result.outcome === "deny" && result.updatedInput !== undefined)) fail("beforeTool cannot stop or replace input while denying"); - if (canonicalEvent === "stop" && (result.outcome === "stop" || result.updatedInput !== undefined || result.additionalContext !== undefined)) fail("stop only accepts continue or deny with a reason"); - if (canonicalEvent === "agentStop" && (result.outcome === "stop" || result.updatedInput !== undefined)) fail("agentStop cannot stop the parent flow or replace input"); - if (canonicalEvent === "agentStop" && target === "codex" && result.additionalContext !== undefined) fail("Codex SubagentStop does not support additionalContext"); - return result; -}; -const encodeOutput = (result)=>{ - if (result === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (result.outcome === "deny") return defined({ - decision: "block", - reason: result.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = defined({ - additionalContext: result.additionalContext, - hookEventName: nativeEvent, - permissionDecision: canonicalEvent === "beforeTool" ? result.outcome === "deny" ? "deny" : "allow" : undefined, - permissionDecisionReason: canonicalEvent === "beforeTool" && result.outcome === "deny" ? result.reason : undefined, - updatedInput: canonicalEvent === "beforeTool" && result.outcome !== "deny" ? result.updatedInput : undefined - }); - return Object.keys(output).length === 1 && output.hookEventName !== undefined ? undefined : { - hookSpecificOutput: output - }; -}; -const decodeOutput = (nativeOutput)=>{ - if (nativeOutput === undefined) return undefined; - if (canonicalEvent === "stop" || canonicalEvent === "agentStop") { - if (nativeOutput.decision === "block") return defined({ - outcome: "deny", - reason: nativeOutput.reason - }); - if (canonicalEvent === "agentStop" && target === "claude" && 0) {} - return undefined; - } - const output = nativeOutput.hookSpecificOutput; - if (!isRecord(output)) fail("native hook output is malformed"); - return defined({ - additionalContext: output.additionalContext, - outcome: output.permissionDecision === "deny" ? "deny" : "continue", - reason: output.permissionDecisionReason, - updatedInput: output.updatedInput - }); -}; -const requireString = (input, field)=>{ - if (typeof input[field] !== "string") fail(`native ${field} must be a string`); -}; -const requireNullableString = (input, field)=>{ - if (input[field] !== null && typeof input[field] !== "string") fail(`native ${field} must be a string or null`); -}; -const validateNativeInput = (input)=>{ - requireString(input, "session_id"); - if (true) requireNullableString(input, "transcript_path"); - else {} - requireString(input, "cwd"); - if (input.hook_event_name !== nativeEvent) fail(`native hook_event_name must equal ${nativeEvent}`); - if (input.prompt_id !== undefined) requireString(input, "prompt_id"); - if (input.permission_mode !== undefined) requireString(input, "permission_mode"); - if (input.model !== undefined) requireString(input, "model"); - if (canonicalEvent === "sessionStart") { - requireString(input, "source"); - return; - } - if (canonicalEvent === "beforeTool" || canonicalEvent === "afterTool") { - requireString(input, "tool_name"); - if (!isRecord(input.tool_input)) fail(`native ${nativeEvent} tool_input must be an object`); - requireString(input, "tool_use_id"); - if (canonicalEvent === "afterTool" && !isRecord(input.tool_response)) fail("native PostToolUse tool_response must be an object"); - return; - } - if (canonicalEvent === "agentStart" || canonicalEvent === "agentStop") { - requireString(input, "agent_id"); - requireString(input, "agent_type"); - if (true) { - requireString(input, "turn_id"); - requireString(input, "model"); - requireString(input, "permission_mode"); - if (![ - "default", - "acceptEdits", - "plan", - "dontAsk", - "bypassPermissions" - ].includes(input.permission_mode)) fail("native permission_mode is invalid"); - } - if (canonicalEvent === "agentStart") return; - if (typeof input.stop_hook_active !== "boolean") fail("native SubagentStop stop_hook_active must be a boolean"); - requireNullableString(input, "agent_transcript_path"); - requireNullableString(input, "last_assistant_message"); - return; - } - if (typeof input.stop_hook_active !== "boolean") fail("native Stop stop_hook_active must be a boolean"); - if (true) requireNullableString(input, "last_assistant_message"); - else {} -}; -const run = async ()=>{ - const handler = Reflect.get(session_start_namespaceObject, "default"); - if (typeof handler !== "function") fail("default export must be a function"); - let raw = ""; - for await (const chunk of process.stdin)raw += chunk; - if (raw.trim().length === 0) fail("stdin must contain exactly one JSON value"); - let input; - try { - input = JSON.parse(raw); - } catch { - fail("stdin must contain exactly one JSON value"); - } - if (!isRecord(input)) fail("stdin JSON value must be an object"); - const simulation = process.env.AGENT_BUNDLE_HOOK_SIMULATION === "1"; - const nativeInput = simulation ? encodeNative(input) : input; - validateNativeInput(nativeInput); - const event = decodeNative(nativeInput); - const result = validateResult(await handler(event, { - nativeEvent: nativeEvent, - nativeInput, - target: target - })); - const nativeOutput = encodeOutput(result); - const output = simulation ? decodeOutput(nativeOutput) : nativeOutput; - if (output !== undefined) process.stdout.write(JSON.stringify(output)); -}; -if (import.meta.main) { - await run().catch((error)=>{ - process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - }); -} - -export {}; diff --git a/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs deleted file mode 100644 index 29189bf45..000000000 --- a/examples/mcp-app/artifact/codex/mcp/mcp-status-073c1634.mjs +++ /dev/null @@ -1,30761 +0,0 @@ -import node_process from "node:process"; - -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/mcp/status.ts -var status_namespaceObject = {}; -__webpack_require__.r(status_namespaceObject); -__webpack_require__.d(status_namespaceObject, { - createStatusServer: () => (createStatusServer), - "default": () => (mcp_status) }); - - -// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs -var stdio_namespaceObject = {}; -__webpack_require__.r(stdio_namespaceObject); -__webpack_require__.d(stdio_namespaceObject, { - StdioServerTransport: () => (stdio_StdioServerTransport) }); - - -//#region rolldown:runtime -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); -var __exportAll = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp(target, Symbol.toStringTag, { value: "Module" }); - } - return target; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { - key = keys[i]; - if (!__hasOwnProp.call(to, key) && key !== except) { - __defProp(to, key, { - get: ((k) => from[k]).bind(null, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - } - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { - value: mod, - enumerable: true -}) : target, mod)); - -//#endregion - -//#region ../core-internal/src/validators/dialects.ts -/** -* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). -*/ -const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); -const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); -const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); -const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); -/** -* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with -* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so -* wire-layer callers can consult it for documents whose dialect may be unsupported. -*/ -function declares2019Dialect($schema) { - return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); -} -/** -* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means -* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the -* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling -* provider's escape hatch in that message. -*/ -function declaredDialect(schema, remedy) { - if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; - const declared = schema.$schema.replace(/#$/, ""); - if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; - if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; - if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; - throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); -} - -//#endregion - -//# sourceMappingURL=dialects-DoSzNhcb.mjs.map - -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function toZod() { - return (schema) => schema; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function util_cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. - const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) - return 0; - return ratio - roundedRatio; -} -const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - // Circular reference detected, return undefined to break the cycle - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function util_esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function util_isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const util_allowsEval = /* @__PURE__*/ util_cached(() => { - // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. - if (globalConfig.jitless) { - return false; - } - // @ts-ignore - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (util_isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - // modified prototype - const prot = ctor.prototype; - if (util_isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - if (o instanceof Map) - return new Map(o); - if (o instanceof Set) - return new Set(o); - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - // @ts-ignore - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); -const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ - "string", - "number", - "bigint", - "boolean", - "symbol", - "undefined", -]))); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; - }); -} -// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. -const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}))(); -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - // `for...in` skips symbols, so a symbol in the mask would select nothing - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - assignProp(newShape, key, currDef.shape[key]); - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values - const existingShape = schema._zod.def.shape; - for (const key of Reflect.ownKeys(shape)) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function merge(a, b) { - if (!b?._zod?.def) { - throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); - } - if (a._zod.def.checks?.length) { - throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - } - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [], - }); - return clone(a, def); -} -function partial(Class, schema, mask, name = "partial") { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(`.${name}() cannot be used on object schemas containing refinements`); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - // the spread copies symbol keys; `for...in` would not reach them - for (const key of Reflect.ownKeys(oldShape)) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function util_required(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key of Reflect.ownKeys(oldShape)) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - }); - return clone(schema, def); -} -// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue === false) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ -function attachSchema(issues, start, inst) { - var _a; - for (let i = start; i < issues.length; i++) { - (_a = issues[i]).schema ?? (_a.schema = inst); - } -} -function finalizeIssue(iss, ctx, config) { - var _a; - // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. - const traits = iss.inst?._zod?.traits; - if (traits?.has("$ZodType")) { - if (traits.has("$ZodCheck")) - (_a = iss).schema ?? (_a.schema = iss.inst); - else - iss.schema = iss.inst; - } - // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. - const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; - const message = iss.message - ? iss.message - : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(schemaError?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"); - const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) { - rest.input = _input; - } - return rest; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - // @ts-ignore - if (input instanceof File) - return "file"; - return "unknown"; -} -const highSurrogate = /[\uD800-\uDBFF]/; -// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. -function codePointLength(str) { - const units = str.length; - if (!highSurrogate.test(str)) - return units; - let count = units; - for (let i = 0; i < units - 1; i++) { - if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - count--; - i++; - } - } - return count; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data) { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "nan" : "number"; - } - case "object": { - if (data === null) { - return "null"; - } - if (Array.isArray(data)) { - return "array"; - } - const obj = data; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// Codec utility functions -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -// instanceof -class util_Class { - constructor(..._args) { } -} -////////// PROTOTYPE INSTALLERS ////////// -// -// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. -/** - * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. - * - * Call this from a `proto` initializer, which runs once per prototype — never per instance. - */ -function util_members(proto, table) { - for (const key in table) { - const desc = Object.getOwnPropertyDescriptor(table, key); - // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was - if (desc.get) - Object.defineProperty(proto, key, { ...desc, enumerable: false }); - // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` - else - defineBound(proto, key, desc.value); - } -} -/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ -function util_own(inst, key, value, enumerable = true) { - Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); - return value; -} -/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ -function hide(inst, key, value) { - return util_own(inst, key, value, false); -} -function defineBound(proto, key, fn) { - Object.defineProperty(proto, key, { - configurable: true, - get() { - // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method - return this == null ? fn : util_own(this, key, fn.bind(this)); - }, - set(value) { - util_own(this, key, value); - }, - }); -} -/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ -function claim(inst, sentinel) { - const proto = Object.getPrototypeOf(inst); - // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. - return sentinel in proto ? undefined : proto; -} -// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. -let installing; -// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. -let broke = false; -const breaker = { - configurable: true, - get() { - broke = true; - return undefined; - }, -}; -/** - * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s - * constructor, computed from the internals object itself and cached there on - * first read. One accessor per constructor rather than one per instance. - */ -function defineLazyInternal(inst, key, compute) { - const proto = Object.getPrototypeOf(inst._zod); - if (key in proto && installing !== inst._zod) { - // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. - installing = undefined; - return; - } - installing = inst._zod; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. - Object.defineProperty(this, key, breaker); - const outer = broke; - broke = false; - try { - const value = compute(this); - // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. - if (broke) - delete this[key]; - else - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - broke = broke || outer; - return value; - } - catch (err) { - // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. - delete this[key]; - broke = broke || outer; - throw err; - } - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - }, - }); -} -/** - * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own - * data property. One accessor per constructor rather than one per instance, because an own accessor - * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. - */ -function installLazyProp(inst, key, make, enumerable) { - const proto = claim(inst, key); - if (!proto) - return; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. - const desc = { configurable: true, writable: true, enumerable, value: undefined }; - Object.defineProperty(this, key, desc); - // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches - desc.value = make(this); - Object.defineProperty(this, key, desc); - return desc.value; - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); - }, - }); -} -/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ -const CONSTANT_CATCH = "~constantCatch"; -/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ -function constantCatch(value) { - const fn = () => value; - fn[CONSTANT_CATCH] = true; - return fn; -} - -var core_a; - -/** A special constant with type `never` */ -const NEVER = /*@__PURE__*/ Object.freeze({ - status: "aborted", -}); -/* Shared descriptor for installing `_zod`; defineProperty reads it - * synchronously, so reusing one object avoids a per-instance allocation. */ -const _zodDesc = { value: undefined, enumerable: false }; -// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error -let _E = "captureStackTrace" in Error ? Error : null; -// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot -function newError(Definition) { - const E = _E; - if (E) { - const saved = E.stackTraceLimit; - if (typeof saved === "number") { - try { - E.stackTraceLimit = 0; - } - catch { - _E = null; - return new Definition(); - } - try { - return new Definition(); - } - finally { - E.stackTraceLimit = saved; - } - } - } - return new Definition(); -} -function $constructor(name, initializer, -/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ -proto, params) { - // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. - const zodProto = {}; - // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. - function Internals(def) { - this.def = def; - this.constr = _; - this.traits = new Set(); - } - Internals.prototype = zodProto; - const protoMembers = proto; - // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. - const initialized = protoMembers && new WeakSet(); - function init(inst, def) { - if (!inst._zod) { - _zodDesc.value = new Internals(def); - try { - Object.defineProperty(inst, "_zod", _zodDesc); - } - finally { - // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. - _zodDesc.value = undefined; - } - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - if (initialized) { - // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. - const own = Object.getPrototypeOf(inst); - const ctorProto = inst._zod.constr.prototype; - let up = own; - while (up && up !== ctorProto) - up = Object.getPrototypeOf(up); - const target = up ?? own; - if (!initialized.has(target)) { - initialized.add(target); - util_members(target, protoMembers); - } - } - // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype - const proto = _.prototype; - for (const k in proto) { - if (!Object.prototype.hasOwnProperty.call(proto, k)) - continue; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - const inst = params?.Parent ? newError(Definition) : this; - init(inst, def); - const deferred = inst._zod.deferred; - if (deferred) { - for (const fn of deferred) { - fn(); - } - // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. - inst._zod.deferred = undefined; - } - // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. - const pp = globalThis.__zod_globalConfig?.postProcessor; - if (pp) - pp(inst); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); -const globalConfig = globalThis.__zod_globalConfig; -function core_config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -class $ZodCyclicError extends Error { - constructor() { - super(`Cannot parse a reference cycle that closes through a transform`); - this.name = "ZodCyclicError"; - } -} -/** Keyed off the context object every schema in one parse call already shares. */ -const STATE = "~memo"; -const NO_ISSUES = []; -// Receivers prefix paths in place, so the cache and every hand-out need their own copies. -function cloneIssues(issues) { - return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); -} -const recursive = /*@__PURE__*/ new WeakMap(); -/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ -function isRecursive(inst, stack) { - const cached = recursive.get(inst); - if (cached !== undefined) - return cached; - // Relative to the walk in progress, so not cached. - if (stack.has(inst)) - return true; - stack.add(inst); - let result = false; - const check = (child) => { - if (!result && child?._zod && isRecursive(child, stack)) - result = true; - }; - const def = inst._zod.def; - const kind = def.type; - switch (kind) { - case "object": { - // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen - for (const key of Reflect.ownKeys(def.shape)) - check(def.shape[key]); - check(def.catchall); - break; - } - case "array": - check(def.element); - break; - case "tuple": - for (const el of def.items) - check(el); - check(def.rest); - break; - case "record": - case "map": - check(def.keyType); - check(def.valueType); - break; - case "set": - check(def.valueType); - break; - case "union": - for (const el of def.options) - check(el); - break; - case "intersection": - check(def.left); - check(def.right); - break; - case "optional": - case "nullable": - case "default": - case "prefault": - case "catch": - case "readonly": - case "nonoptional": - case "promise": - case "success": - check(def.innerType); - break; - case "pipe": - check(def.in); - check(def.out); - break; - case "function": - check(def.input); - check(def.output); - break; - // reading `_zod.innerType` resolves the getter once and caches it - case "lazy": - check(inst._zod.innerType); - break; - // a leaf by choice: `parts` are regex fragments, not data positions - case "template_literal": - // leaves - case "string": - case "number": - case "int": - case "boolean": - case "bigint": - case "symbol": - case "undefined": - case "null": - case "void": - case "never": - case "any": - case "unknown": - case "date": - case "nan": - case "enum": - case "literal": - case "file": - case "transform": - case "custom": - break; - default: { - // a new built-in kind becomes a compile error here - kind; - // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code - for (const key in def) { - const desc = Object.getOwnPropertyDescriptor(def, key); - if (!desc || desc.get) - continue; - const value = desc.value; - if (!value || typeof value !== "object") - continue; - if (value._zod) - check(value); - else if (Array.isArray(value)) - for (const el of value) - check(el); - } - } - } - stack.delete(inst); - recursive.set(inst, result); - return result; -} -/** - * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. - * Exported for `z.compile`, which refuses to compile such a schema: cycle - * breaking is driven from here off state keyed on the parse context, and a - * generated fast path has no context to key on. - */ -function isRecursiveSchema(inst) { - return isRecursive(inst, new Set()); -} -function bucketFor(state, inst) { - let bucket = state.buckets.get(inst); - if (!bucket) { - bucket = new Map(); - state.buckets.set(inst, bucket); - } - return bucket; -} -// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. -let handoff; -// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. -const memoizer_open = []; -const memoizer_memo = { - alloc(_inst, payload, empty) { - const bucket = handoff; - if (!bucket) - return empty; - handoff = undefined; - const entry = { value: empty, issues: null }; - bucket.set(payload.value, entry); - memoizer_open.push(entry); - return empty; - }, - guard(inst) { - var _a; - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. - if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) - throw new $ZodCyclicError(); - return base(payload, ctx); - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, - attach(inst) { - var _a; - let isRecursiveInst; - // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes - let lastCtx; - let lastBucket; - // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - if (isRecursiveInst === undefined) { - isRecursiveInst = isRecursive(inst, new Set()); - if (!isRecursiveInst) { - // Nothing here can ever fire, so take it back out. - inst._zod.parse = base; - if (inst._zod.run === wrapped) - inst._zod.run = base; - return base(payload, ctx); - } - } - const input = payload.value; - if (input === null || typeof input !== "object") - return base(payload, ctx); - let state = ctx[STATE]; - if (!state) { - state = { buckets: new Map(), backEdges: undefined }; - ctx[STATE] = state; - } - let bucket; - if (lastCtx === ctx) { - bucket = lastBucket; - } - else { - bucket = bucketFor(state, inst); - lastCtx = ctx; - lastBucket = bucket; - } - const hit = bucket.get(input); - if (hit) { - payload.value = hit.value; - if (hit.issues) { - if (hit.issues.length) - payload.issues.push(...cloneIssues(hit.issues)); - } - else { - // Still being parsed: its own checks cover it, so skip them here. - payload.memo = true; - state.backEdges ?? (state.backEdges = new Set()); - state.backEdges.add(hit.value); - } - return payload; - } - handoff = bucket; - const depth = memoizer_open.length; - const result = base(payload, ctx); - handoff = undefined; - // A container that rejected its input outright allocated nothing. - const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; - // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. - if (result instanceof Promise) { - return result.then((r) => { - if (entry) - entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; - return r; - }); - } - if (entry) - entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; - return result; - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, -}; -/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ -function memoizer() { - return memoizer_memo; -} -/** Whether this value is a node a back-edge resolved to before it finished. */ -function isBackEdge(ctx, value) { - const backEdges = ctx[STATE]?.backEdges; - return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); -} - - -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const cuid = /^[cC][0-9a-z]{6,}$/; -const cuid2 = /^[0-9a-z]+$/; -const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; -const xid = /^[0-9a-vA-V]{20}$/; -const ksuid = /^[A-Za-z0-9]{27}$/; -const nanoid = /^[a-zA-Z0-9_-]{21}$/; -function nanoidOfLength(length) { - return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); -} -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ -const extendedDuration = /^[-+]?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)?)??$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. - * - * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -const uuid = (version) => { - if (!version) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); -const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); -const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); -/** Practical email validation */ -const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -/** The classic emailregex.com regex for RFC 5322-compliant emails */ -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. -const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const regexes_ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/; -const mac = (delimiter) => { - const escapedDelim = util.escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const regexes_base64url = /^[A-Za-z0-9_-]*$/; -// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address -// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; -const httpProtocol = /^https?$/; -// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 -const e164 = /^\+[1-9]\d{6,14}$/; -// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). -const creditCard = /^\d(?:[ -]?\d){11,18}$/; -const dateSource = `(?:(?:\\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])))`; -/** Anchors a pattern source. The interpolation lives here rather than at the call site because - * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it - * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ -function regexes_anchor(source) { - return new RegExp(`^${source}$`); -} -const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : args.seconds - ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function regexes_time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetime(args) { - const opts = ["Z"]; - // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them - const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; - const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const regexes_string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number = /^-?\d+(?:\.\d+)?$/; -const regexes_boolean = /^(?:true|false)$/i; -const _null = /^null$/i; - -const _undefined = /^undefined$/i; - -// regex for string with no uppercase letters -const lowercase = /^[^A-Z]*$/; -// regex for string with no lowercase letters -const uppercase = /^[^a-z]*$/; -// regex for hexadecimal strings (any length) -const regexes_hex = /^[0-9a-fA-F]*$/; -// Hash regexes for different algorithms and encodings -// Helper function to create base64 regex with exact length and padding -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -// Helper function to create base64url regex with exact length (no padding) -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -// MD5 (16 bytes): base64 = 24 chars total (22 + "==") -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); -const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); -// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); -const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); -// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); -const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); -// SHA384 (48 bytes): base64 = 64 chars total (no padding) -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); -const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); -// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); -const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); - -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ -const _whenHasSize = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; -}; -/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ -const _whenHasLength = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; -}; -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = -/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN - def.value !== BigInt(0) && payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: util.getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. - const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. - const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 - ? codePointLength(input) - : units; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. - const length = typeof input === "string" && units >= def.length && units <= def.length * 2 - ? codePointLength(input) - : units; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - // `String.prototype.includes(sub, position)` matches `sub` at `position` - // OR LATER, so the pattern must allow at least `position` leading chars - // (`{N,}`), not exactly `position` chars (`{N}`). - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}))); -const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -class Doc { - constructor(args = [], closed = {}) { - this.content = []; - this.indent = 0; - this.args = args; - this.closed = closed; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const content = this?.content ?? [``]; - const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); - return factory(...Object.values(this.closed)); - } -} - - - -/* Computing the message eagerly is expensive (pretty-printed JSON of all - * issues), so defer it until first read. The accessor functions and - * descriptors are shared across instances to keep error construction - * cheap; the computed message is cached on the internals object. The - * setter preserves plain assignment semantics for consumers that - * overwrite `message`. */ -function _getMessage() { - const internals = this._zod; - internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); - return internals.message; -} -function _setMessage(value) { - this._zod.message = value; -} -const _messageDesc = { - get: _getMessage, - set: _setMessage, - enumerable: true, - configurable: true, -}; -const errors_zodDesc = { value: undefined, enumerable: false }; -const _issuesDesc = { value: undefined, enumerable: false }; -/* Prototypes that already carry the lazy `toString`. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -const errors_initializer = (inst, def) => { - inst.name = "$ZodError"; - errors_zodDesc.value = inst._zod; - Object.defineProperty(inst, "_zod", errors_zodDesc); - _issuesDesc.value = def; - Object.defineProperty(inst, "issues", _issuesDesc); - // Clear the shared slots; a retained `value` pins the last error's issues. - errors_zodDesc.value = undefined; - _issuesDesc.value = undefined; - Object.defineProperty(inst, "message", _messageDesc); - /* `toString` lives as a non-enumerable lazy getter on the shared - * prototype; on first access it caches a per-instance closure so - * detached usage still works. */ - const proto = Object.getPrototypeOf(inst); - if (!_installedToString.has(proto)) { - _installedToString.add(proto); - Object.defineProperty(proto, "toString", { - configurable: true, - enumerable: false, - get() { - const value = () => this.message; - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - }, - }); - } -}; -const $ZodError = $constructor("$ZodError", errors_initializer); -const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { - Parent: Error, -}); -/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member - * ("toString", "constructor") would otherwise read through to the prototype, and assigning - * "__proto__" would hit the setter instead of creating a key. */ -function errors_node(obj, key, make) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - if (key === "__proto__") { - Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); - } - else { - obj[key] = make(); - } - } - return obj[key]; -} -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. - if (el === "_errors") { - if (terminal) - curr._errors.push(mapper(issue)); - i++; - continue; - } - // A path element may collide with an inherited property name such as - // "__proto__" or "constructor". Truthiness checks read the prototype - // (so no node is created, then ._errors.push throws), and bracket - // assignment of "__proto__" hits the setter instead of creating an - // own key. Guard the read with hasOwnProperty and create the node - // with defineProperty so any path element becomes a real own key. - if (!Object.prototype.hasOwnProperty.call(curr, el)) { - Object.defineProperty(curr, el, { - value: { _errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - const node = curr[el]; - if (terminal) { - node._errors.push(mapper(issue)); - } - curr = node; - i++; - } - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - // el may collide with an inherited property name ("__proto__", - // "constructor", ...); ??= reads the prototype so the node is never - // created and curr.errors.push throws. Guard with hasOwnProperty and - // create the node with defineProperty so "__proto__" becomes a real - // own key rather than invoking the prototype setter. - if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { - Object.defineProperty(curr.properties, el, { - value: { errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - - - - -// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. -function finalizeParams(callee, params) { - return { callee: params?.callee ?? callee, Err: params?.Err }; -} -const parse_parse = (_Err) => { - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, _params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); -const parse_parseAsync = (_Err) => { - const fn = async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); -// registry mirrors of the compiler's sentinels, so this module never imports the compiler -const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); -const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); -// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. -const parse_validate = ((schema, value, _ctx) => { - const validator = schema._zod.bag.validator; - if (validator !== undefined && validator(value) !== COMPILE_INVALID) - return true; - return validateFallback(schema, value, _ctx); -}); -function validateFallback(schema, value, _ctx) { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const fallbackRun = schema._zod.bag.fallbackRun; - let result; - if (fallbackRun) { - // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound - ctx[COMPILE_FALLBACK] = true; - result = fallbackRun({ value, issues: [] }, ctx); - } - else { - result = schema._zod.run({ value, issues: [] }, ctx); - } - if (result instanceof Promise) { - throw new core.$ZodAsyncError(); - } - return result.issues.length === 0; -} -// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw -const parse_validateAsync = async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length === 0; -}; -const parse_encode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return parse(schema, value, ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const encode = /* @__PURE__*/ parse_encode($ZodRealError); -const parse_decode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - return parse(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decode = /* @__PURE__*/ parse_decode($ZodRealError); -const parse_encodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); - }; - return fn; -}; -const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); -const parse_decodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); - -const versions_version = { - major: 4, - minor: 5, - patch: 4, -}; - - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const defChecks = inst._zod.def.checks; - // if inst is itself a checks.$ZodCheck, run it as a check - const checks = inst._zod.traits.has("$ZodCheck") - ? [inst, ...(defChecks ?? [])] - : defChecks?.length - ? [...defChecks] - : []; - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - if (payload.memo) - return payload; - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) - continue; - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - // abort if the canary is aborted - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - // run checks first, then - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - // run canary initial pass (no checks) - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - // forward - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } -}, { - // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. - get "~standard"() { - return hide(this, "~standard", standardProps(this)); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, -}); -/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ -const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; -function standardProps(inst) { - return { - validate: (value) => { - try { - return toStandardResult(safeParse(inst, value)); - } - catch (_) { - return safeParseAsync(inst, value).then(toStandardResult); - } - }, - vendor: "zod", - version: 1, - }; -} - -const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } - else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -/** The `://` guard rejected the input before the URL constructor saw it. */ -const URL_BAD_FORMAT = 1; -/** The URL constructor rejected the input. */ -const URL_UNPARSEABLE = 2; -/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ -function parseURLObject(trimmed, def) { - // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted - if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { - return URL_BAD_FORMAT; - } - try { - // @ts-ignore - return new URL(trimmed); - } - catch { - return URL_UNPARSEABLE; - } -} -const asciiTabOrNewline = /[\t\n\r]/g; -/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ -function stripTabAndNewline(value) { - return value.replace(asciiTabOrNewline, ""); -} -function urlHostnameOk(url, hostname) { - hostname.lastIndex = 0; - return hostname.test(url.hostname); -} -function urlProtocolOk(url, protocol) { - protocol.lastIndex = 0; - return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); -} -const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - // Trim whitespace from input - const trimmed = payload.value.trim(); - const url = parseURLObject(trimmed, def); - if (url === URL_BAD_FORMAT) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (url === URL_UNPARSEABLE) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (def.hostname && !urlHostnameOk(url, def.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - if (def.protocol && !urlProtocolOk(url, def.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - // Set the output value based on normalize flag - payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) - throw new Error(`Invalid nanoid length: ${def.length}`); - def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); - $ZodStringFormat.init(inst, def); -}); -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema - if (def.local || def.precision === -1) { - inst._zod.bag.laxFormat = true; - inst._zod.onattach.push((s) => { - s._zod.bag.laxFormat = true; - }); - } -}); -const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = regexes_date); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes_time(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ -const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; -function isValidIPv6(value) { - if (!ipv6Alphabet.test(value)) - return false; - try { - // @ts-ignore - new URL(`http://[${value}]`); - return true; - } - catch { - return false; - } -} -const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes_ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - if (!isValidIPv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}))); -const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -function isValidCIDRv6(value) { - const parts = value.split("/"); - if (parts.length !== 2) - return false; - const [address, prefix] = parts; - if (!prefix) - return false; - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - return false; - if (prefixNum < 0 || prefixNum > 128) - return false; - return isValidIPv6(address); -} -const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (!isValidCIDRv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - // atob ignores whitespace, so reject it up front. - if (/\s/.test(data)) - return false; - if (data.length % 4 !== 0) - return false; - try { - // @ts-ignore - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!regexes_base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -////////////////////////////// ZodCreditCard ////////////////////////////// -const CC_SANITIZE = /[- ]/g; -/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ -function isLuhnAlgo(digits) { - let length = digits.length; - let bit = 1; - let sum = 0; - while (length) { - const value = +digits[--length]; - bit ^= 1; - sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; - } - return sum % 10 === 0; -} -function isValidCreditCard(input) { - if (!regexes.creditCard.test(input)) - return false; - return isLuhnAlgo(input.replace(CC_SANITIZE, "")); -} -const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { - // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. - def.pattern ?? (def.pattern = regexes.creditCard); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidCreditCard(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "credit_card", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - // @ts-ignore - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? String(input) - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checks -}); -const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes_boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { - checks.$ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}))); -const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.undefined; - inst._zod.values = new Set([undefined]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}))); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handlePropertyResult(result, final, key, input, optin, optout) { - const isPresent = key in input; - const isOptionalOut = optout === "optional"; - // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. - if (!isPresent && isOptionalOut && optin === "optional") { - return; - } - if (result.issues.length) { - // For optional-in/out schemas, ignore errors on absent keys. - if (optin !== undefined && isOptionalOut && !isPresent) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && optin === undefined) { - if (!result.issues.length) { - final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [key], - }); - } - return; - } - if (result.value === undefined) { - if (isPresent) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -// one shared instance; a fresh [] per schema cost 56 bytes retained -const NO_SYMBOL_KEYS = []; -function normalizeDef(def) { - const keys = Object.keys(def.shape); - const ownSymbols = Object.getOwnPropertySymbols(def.shape); - const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; - // aliases `keys` when there are no symbols, so a string-only shape keeps one array - const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; - for (const k of allKeys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - allKeys, - symbolKeys, - // string-only: handleCatchall matches it against `for...in`, which never yields a symbol - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const optin = _catchall.optin; - const optout = _catchall.optout; - for (const key in input) { - // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. - if (keySet.has(key)) - continue; - // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. - if (key === "__proto__") { - if (t === "never") - unrecognized.push(key); - continue; - } - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. - continue: true, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. -const propShapes = new WeakMap(); -const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - // const sh = def.shape; - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - propShapes.set(def, sh); - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - propShapes.set(def, newSh); - return newSh; - }, - }); - } - const _normalized = util_cached(() => normalizeDef(def)); - defineLazyInternal(inst, "propValues", (zod) => { - const shape = zod.def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - if (!Object.prototype.hasOwnProperty.call(propValues, key)) { - assignProp(propValues, key, new Set()); - } - for (const v of field.values) - propValues[key].add(v); - // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. - if (field.optin !== undefined) - propValues[key].add(undefined); - } - } - return propValues; - }); - const isObject = util_isObject; - const catchall = def.catchall; - let value; - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const proms = []; - const shape = value.shape; - for (const key of value.allKeys) { - if (key === "__proto__") - continue; - const el = shape[key]; - const optin = el._zod.optin; - const optout = el._zod.optout; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = util_cached(() => normalizeDef(def)); - const memo = globalConfig.memoizer; - const generateFastpass = (shape) => { - const normalized = _normalized.value; - const syms = normalized.symbolKeys; - // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope - const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); - const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - // Prefixes in place, like util.prefixIssues does for every interpreted path. - const prefixStr = (id, k) => ` - for (let i = 0; i < ${id}.issues.length; i++) { - const iss = ${id}.issues[i]; - iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; - payload.issues.push(iss); - }`; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.allKeys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); - for (const key of normalized.allKeys) { - if (key === "__proto__") - continue; - const id = ids[key]; - const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); - const isPresent = `${k} in input`; - const schema = shape[key]; - const optin = schema?._zod?.optin; - const isOptionalIn = optin !== undefined; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(k)};`); - if (isOptionalIn && isOptionalOut) { - // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. - const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; - doc.write(` - const ${id}_present = ${isPresent}; - if (!${id}.issues.length || ${id}_present) { - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${assign}) { - newResult[${k}] = ${id}.value; - } - } - - `); - } - else if (!isOptionalIn) { - doc.write(` - const ${id}_present = ${isPresent}; - if (${id}.issues.length) {${prefixStr(id, k)} - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - newResult[${k}] = ${id}.value; - } - - `); - } - else { - doc.write(` - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${id}.value === undefined) { - if (${isPresent}) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone - return doc.compile(); - }; - let fastpass; - const isObject = util_isObject; - const jit = !globalConfig.jitless; - const allowsEval = util_allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") - ? "defaulted" - : zod.def.options.some((o) => o._zod.optin !== undefined) - ? "optional" - : undefined); - defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazyInternal(inst, "values", (zod) => { - if (zod.def.options.every((o) => o._zod.values)) { - return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - if (zod.def.options.every((o) => o._zod.pattern)) { - const patterns = zod.def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const matches = []; - for (let i = 0; i < results.length; i++) { - if (results[i].issues.length === 0) - matches.push(i); - } - if (matches.length === 1) { - final.value = results[matches[0]].value; - return final; - } - if (matches.length === 0) { - // No matches - same as regular union - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), - }); - } - else { - // Multiple matches - exclusive union failure - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - matches, - }); - } - return final; -} -const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}))); -/** Returns the option of `union` whose discriminator claims `value`. */ -function getDiscriminatedOption(union, value) { - const internals = union._zod; - let map = internals.bag.optionsMap; - if (!map) { - map = new Map(); - const { options, discriminator } = internals.def; - for (const option of options) { - // First declaration wins, matching the order the parse path resolves a duplicate in. - for (const v of option._zod.propValues?.[discriminator] ?? []) - if (!map.has(v)) - map.set(v, option); - } - internals.bag.optionsMap = map; - } - return map.get(value); -} -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazyInternal(inst, "propValues", (zod) => { - const propValues = {}; - for (const option of zod.def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!Object.prototype.hasOwnProperty.call(propValues, k)) { - assignProp(propValues, k, new Set()); - } - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. - def.options.forEach((option, i) => { - const propShape = propShapes.get(option._zod.def); - if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { - throw new Error(`Invalid discriminated union option at index "${i}"`); - } - }); - const disc = util_cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util_isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - // Fall back to union matching when the fast discriminator path fails: - // - explicitly enabled via unionFallback, or - // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions - if (def.unionFallback || ctx.direction === "backward") { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function schemas_mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) - delete newObj.__proto__; - for (const key of sharedKeys) { - if (key === "__proto__") - continue; - const sharedValue = schemas_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = schemas_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. - const unrecKeys = new Map(); - let unrecIssue; - const keyIssues = new Map(); - const collect = (iss, side) => { - let keys; - if (iss.code === "unrecognized_keys" && !iss.path?.length) { - unrecIssue ?? (unrecIssue = iss); - keys = iss.keys; - } - else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { - const k = String(iss.path[0]); - if (!keyIssues.has(k)) - keyIssues.set(k, iss); - keys = [k]; - } - else { - return false; - } - for (const k of keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k)[side] = true; - } - return true; - }; - for (const iss of left.issues) { - if (!collect(iss, "l")) - result.issues.push(iss); - } - for (const iss of right.issues) { - if (!collect(iss, "r")) - result.issues.push(iss); - } - // Report only keys rejected by BOTH sides - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length) { - const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; - if (aggregated.length) - result.issues.push({ ...unrecIssue, keys: aggregated }); - for (const k of bothKeys) { - if (!aggregated.includes(k) && keyIssues.has(k)) - result.issues.push(keyIssues.get(k)); - } - } - const merged = schemas_mergeValues(left.value, right.value); - if (!merged.valid) { - if (aborted(result)) - return result; - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; - const proms = []; - const optinStart = getTupleOptStart(items, "optin"); - const optoutStart = getTupleOptStart(items, "optout"); - if (!def.rest) { - if (input.length < optinStart) { - payload.issues.push({ - code: "too_small", - minimum: optinStart, - inclusive: true, - input, - inst, - origin: "array", - }); - return payload; - } - if (input.length > items.length) { - payload.issues.push({ - code: "too_big", - maximum: items.length, - inclusive: true, - input, - inst, - origin: "array", - }); - } - } - // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. - const itemResults = new Array(items.length); - for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((rr) => { - itemResults[i] = rr; - })); - } - else { - itemResults[i] = r; - } - } - if (def.rest) { - let i = items.length - 1; - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ value: el, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((r) => handleTupleResult(r, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); - } - return handleTupleResults(itemResults, payload, items, input, optoutStart); - }; -}))); -function getTupleOptStart(items, key) { - for (let i = items.length - 1; i >= 0; i--) { - // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. - const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; - if (!omittable) - return i + 1; - } - return 0; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...util.prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleTupleResults(itemResults, final, items, input, optoutStart) { - // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. - for (let i = 0; i < items.length; i++) { - const r = itemResults[i]; - const isPresent = i < input.length; - // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. - if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { - final.value.length = i; - break; - } - if (r.issues.length) { - if (!isPresent && i >= optoutStart) { - final.value.length = i; - break; - } - final.issues.push(...util.prefixIssues(i, r.issues)); - } - final.value[i] = r.value; - } - // Drop trailing slots that produced `undefined` for absent input - // (the array analog of an absent optional key on an object). The - // `i >= input.length` floor is critical: an explicit `undefined` - // *inside* the input must be preserved even when the schema is - // optional-out (e.g. `z.string().or(z.undefined())` accepting an - // explicit undefined value). - for (let i = final.value.length - 1; i >= input.length; i--) { - if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { - final.value.length = i; - } - else { - break; - } - } - return final; -} -const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values && !def.partial) { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - // A declared __proto__ is stripped but is not an unrecognized key. - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - continue; - } - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - if (def.mode === "loose") { - // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into - if (key === "__proto__") - continue; - payload.value[key] = input[key]; - } - else { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - else { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. - let unrecognized; - // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - // Pass through unchanged - payload.value[key] = input[key]; - } - else if (values) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - else { - // Default "strict" behavior: error on invalid key - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - if (valueResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - const values = new Set(def.values); - inst._zod.values = values; - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(def.values.length - ? `^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$` - : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - // @ts-ignore - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - globalConfig.memoizer?.guard(inst); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(payload, result) { - // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. - payload.value = result.issues.length ? undefined : result.value; - return payload; -} -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - inst._zod.optout = "optional"; - defineLazyInternal(inst, "values", (zod) => { - const values = zod.def.innerType._zod.values; - return values ? new Set([...values, undefined]) : undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. - if (def.innerType._zod.optin !== "defaulted") - return payload; - // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) - return result.then((result) => handleOptionalResult(payload, result)); - return handleOptionalResult(payload, result); - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - // Call parent init - inherits optin/optout = "optional" - $ZodOptional.init(inst, def); - // Override values/pattern to NOT add undefined - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); - // Override parse to just delegate (no undefined handling) - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazyInternal(inst, "values", (zod) => { - return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - // Forward direction (decode): allow null to pass through - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply defaults for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - // Forward direction: continue with default handling - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply prefault for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => { - const v = zod.def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new core.$ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}))); -function handleCatchResult(payload, result, def, ctx) { - if (!result.issues.length) { - payload.value = result.value; - // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. - if (result.memo) - payload.memo = true; - return payload; - } - // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. - payload.value = def.catchValue({ - ...result, - value: payload.value, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - }, - input: payload.value, - }); - return payload; -} -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply catch logic - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) { - return result.then((result) => handleCatchResult(payload, result, def, ctx)); - } - return handleCatchResult(payload, result, def, ctx); - }; -}); -const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}))); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. - if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { - // prevent further checks - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}))); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - // prevent further checks - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - // Check if transform added any issues - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { - $ZodPipe.init(inst, def); -}); -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. - if (!payload.memo) - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - // is Zod schema - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || util.primitiveTypes.has(typeof part)) { - regexParts.push(util.escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}))); -const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. - Object.defineProperty(inst, "_def", { value: def }); - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. - return Object.defineProperty(function (...args) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return Object.defineProperty(async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - // Check if output is a promise type to determine if we should use async implementation - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}))); -const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}))); -const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. - defineLazy(inst._zod, "innerType", () => { - const d = def; - if (!d._cachedInner) - d._cachedInner = def.getter(); - return d._cachedInner; - }); - defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); - defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); - defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); - defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -var registries_a; -const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); -const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registries_registry() { - return new $ZodRegistry(); -} -(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - - - - - -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link _cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _creditCard(Class, params) { - return new Class({ - type: "string", - format: "credit_card", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = (/* unused pure expression or super */ null && ({ - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -})); -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_undefined(Class, params) { - return new Class({ - type: "undefined", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_null(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ - type: "any", - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class, params) { - return new Class({ - type: "void", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class, params) { - return new Class({ - type: "date", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class, params) { - return new Class({ - type: "nan", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return _gt(0, params); -} -// negative -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return _lt(0, params); -} -// nonpositive -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new checks.$ZodCheckMaxSize({ - check: "max_size", - ...util.normalizeParams(params), - maximum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new checks.$ZodCheckMinSize({ - check: "min_size", - ...util.normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new checks.$ZodCheckSizeEquals({ - check: "size_equals", - ...util.normalizeParams(params), - size, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema, params) { - return new checks.$ZodCheckProperty({ - check: "property", - property, - schema, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _properties(shape) { - return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new checks.$ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -// @__NO_SIDE_EFFECTS__ -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -// slugify -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...util.normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options: options, - discriminator, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -// @__NO_SIDE_EFFECTS__ -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof schemas.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class, params) { - return new Class({ - type: "file", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); - }, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class, fn, _params) { - const norm = util.normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// same as _custom but defaults to abort:false -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = _check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function api_meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = util.normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? schemas.$ZodCodec; - const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; - const _String = Classes.String ?? schemas.$ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - codec._zod.bag.truthy = truthyArray; - codec._zod.bag.falsy = falsyArray; - codec._zod.bag.case = params.case ?? "insensitive"; - return codec; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = util.normalizeParams(_params); - const def = { - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - - - -function assignProps(target, ...sources) { - for (const source of sources) { - for (const key of Reflect.ownKeys(source)) { - if (Object.prototype.propertyIsEnumerable.call(source, key)) { - assignProp(target, key, source[key]); - } - } - } - return target; -} -// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { -// return { -// processor: inputs.processor, -// metadataRegistry: inputs.metadata ?? globalRegistry, -// target: inputs.target ?? "draft-2020-12", -// unrepresentable: inputs.unrepresentable ?? "throw", -// }; -// } -function initializeContext(params) { - // Normalize target: convert old non-hyphenated versions to hyphenated versions - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - sharedDefsExtractedFor: undefined, - sharedEmitDoneFor: undefined, - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - intersections: [], - deferred: [], - external: params?.external ?? undefined, - }; -} -/** - * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws - * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a - * custom JSON Schema was written into `json`, in which case the caller must not write its own. - */ -function handleUnrepresentable(schema, ctx, json, params, message) { - const result = typeof ctx.unrepresentable === "function" - ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) - : ctx.unrepresentable; - if (result === "any") - return false; - if (result === undefined || result === "throw") - throw new Error(message); - Object.assign(json, result); - return true; -} -function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - // check for schema in seens - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - ctx.sharedDefsExtractedFor = undefined; - ctx.sharedEmitDoneFor = undefined; - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - // Also set ref if processor didn't (for inheritance) - if (!result.ref) - result.ref = parent; - to_json_schema_process(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - // metadata - const meta = ctx.metadataRegistry.get(schema); - if (meta) - assignProps(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (ctx.io === "input" && "_prefault" in result.schema) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from ctx.seen in case it was overwritten - const _result = ctx.seen.get(schema); - return _result.schema; -} -// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. -function encodeJSONPointerSegment(segment) { - return segment.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function extractDefs(ctx, schema -// params: EmitParams -) { - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. - if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) - return; - // Track ids to detect duplicates across different schemas - const idToSchema = new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy - // external is configured - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; - // check if schema is in the external registry - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` - if (entry[1] === root && !entry[1].schema.id) { - return { ref: uriPrefix }; - } - // self-contained schema - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; - }; - // stored cached version in `def` property remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } - if (ctx.external) - ctx.sharedDefsExtractedFor = ctx.external; -} -/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ -function compactTypeUnion(schema) { - const options = schema.anyOf; - if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) - return; - const types = []; - for (const option of options) { - if (!option || typeof option !== "object") - return; - // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. - compactTypeUnion(option); - const keys = Object.keys(option); - if (keys.length !== 1 || keys[0] !== "type") - return; - const type = option.type; - for (const member of Array.isArray(type) ? type : [type]) { - if (typeof member !== "string") - return; - if (!types.includes(member)) - types.push(member); - } - } - delete schema.anyOf; - // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. - schema.type = types.length === 1 ? types[0] : types; -} -/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, - * an annotation like `description` — makes a member unfoldable, so a constraint this does not - * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ -const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); -const UNION_KEYS = ["oneOf", "anyOf"]; -/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ -function undeclaredConstraint(member) { - const extra = member.additionalProperties; - if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) - return null; - return Object.keys(extra).length ? extra : null; -} -/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ -function foldObjects(members) { - const objects = []; - for (const member of members) { - // A boolean subschema is legal JSON Schema and carries no keywords to fold. - if (typeof member !== "object" || member.type !== "object") - return null; - for (const key in member) { - if (!FOLDABLE_KEYS.has(key)) - return null; - } - objects.push(member); - } - const properties = {}; - const required = new Set(); - for (const object of objects) { - for (const key in object.properties) { - // `in` would report a `__proto__` key as already present via the prototype chain and skip it. - if (Object.prototype.hasOwnProperty.call(properties, key)) - continue; - // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. - const parts = []; - for (const other of objects) { - const part = other.properties?.[key] ?? undeclaredConstraint(other); - if (part === null || part === undefined) - continue; - if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) - parts.push(part); - } - const merged = parts.length === 1 - ? parts[0] - : (foldObjects(parts) ?? { allOf: parts }); - assignProp(properties, key, merged); - } - for (const key of object.required ?? []) - required.add(key); - } - const folded = { type: "object", properties }; - if (required.size) - folded.required = [...required]; - // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. - if (objects.every((object) => object.additionalProperties === false)) { - folded.additionalProperties = false; - } - else { - const constraints = []; - for (const object of objects) { - const constraint = undeclaredConstraint(object); - if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) - constraints.push(constraint); - } - if (constraints.length === 1) - folded.additionalProperties = constraints[0]; - else if (constraints.length > 1) - folded.additionalProperties = { allOf: constraints }; - } - return folded; -} -/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two - * closed object members reject each other's keys and the schema validates nothing. Zod's parser - * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when - * *every* side rejects it — so the emitted schema has to pool them too, and folding the members - * into one object is the encoding that says so on every target. - * - * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` - * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it - * keeps its reference and its own closedness rather than being inlined as a stale copy. */ -function foldIntersection(json) { - const allOf = json.allOf; - if (!Array.isArray(allOf) || allOf.length < 2) - return; - // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. - for (const key of FOLDABLE_KEYS) - if (key in json) - return; - // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. - const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); - let folded = null; - if (!unions.length) { - folded = foldObjects(allOf); - } - else { - const union = unions[0]; - const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); - if (Object.keys(union).length !== 1) - return; - const rest = allOf.filter((m) => m !== union); - const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); - if (branches.some((b) => !b)) - return; - folded = { [keyword]: branches }; - } - if (!folded) - return; - delete json.allOf; - assignProps(json, folded); -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // flatten refs - inherit properties from parent schemas - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - // already processed - if (seen.ref === null) - return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; // prevent infinite recursion - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - // merge referenced schema into current - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - // older drafts can't combine $ref with other properties - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - assignProps(schema, refSchema); - } - // restore child's own properties (child wins) - assignProps(schema, _cached); - const isParentRef = zodSchema._zod.parent === ref; - // For parent chain, child is a refinement - remove parent-only properties - if (isParentRef) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema[key]; - } - } - } - // When ref was extracted to $defs, remove properties that match the definition - if (refSchema.$ref && refSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { - delete schema[key]; - } - } - } - } - // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - // Ensure parent is processed first so its def has inherited properties - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - // De-duplicate with parent's definition - if (parentSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema[key]; - } - } - } - } - } - // execute overrides - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - if (ctx.target !== "openapi-3.0") { - for (const entry of ctx.seen.entries()) { - compactTypeUnion(entry[1].def ?? entry[1].schema); - } - } - for (const rewrite of ctx.deferred) - rewrite(); - // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. - if (ctx.intersections.length) { - const carriers = new Map(); - for (const seen of ctx.seen.values()) { - for (const json of [seen.schema, seen.def]) { - const allOf = json?.allOf; - if (!Array.isArray(allOf)) - continue; - const existing = carriers.get(allOf); - if (existing) - existing.push(json); - else - carriers.set(allOf, [json]); - } - } - for (const allOf of ctx.intersections) { - for (const json of carriers.get(allOf) ?? []) - foldIntersection(json); - } - } - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") { - // OpenAPI 3.0 schema objects should not include a $schema property - } - else { - // Arbitrary string values are allowed but won't have a $schema property set - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs - assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); - // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== undefined && result.id === rootMetaId) - delete result.id; - // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. - const defs = ctx.external?.defs ?? {}; - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - assignProp(defs, seen.defId, seen.def); - } - } - } - if (ctx.external) - ctx.sharedEmitDoneFor = ctx.external; - // set definitions in result - if (ctx.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault" || - def.type === "catch") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) - return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -/** - * Creates a toJSONSchema method for a schema instance. - * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. - */ -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - - - - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set -}; -// ==================== SIMPLE TYPE PROCESSORS ==================== -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids - if (format === "time" || laxFormat) { - delete json.format; - } - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const patternList = [...patterns]; - if (patternList.length === 1) - json.pattern = patternList[0].source; - else if (patternList.length > 1) { - json.allOf = [ - ...patternList.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - // when both minimum and exclusiveMinimum exist, pick the more restrictive one - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) { - if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - else if (typeof minimum === "number") { - json.minimum = minimum; - } - if (exMax) { - if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - else if (typeof maximum === "number") { - json.maximum = maximum; - } - if (typeof multipleOf === "number") { - // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. - if (Number.isFinite(multipleOf) && multipleOf !== 0) - json.multipleOf = Math.abs(multipleOf); - else - handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); - } -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); -}; -const symbolProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); -}; -const voidProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const dateProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - // an empty enum accepts nothing, same as z.never() - if (values.length === 0) { - json.not = {}; - return; - } - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // a literal with no values accepts nothing, same as z.never() - if (def.values.length === 0) { - json.not = {}; - return; - } - const vals = []; - for (const val of def.values) { - if (val === undefined) { - // a custom schema replaces the whole literal, so there is nothing left to accumulate - if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) - return; - // otherwise do not add to vals - } - else if (typeof val === "bigint") { - if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) - return; - vals.push(Number(val)); - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - Object.assign(_json, file); // shared props at root - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); -}; -const functionProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); -}; -const transformProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); -}; -const mapProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); -}; -const setProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); -}; -// ==================== COMPOSITE TYPE PROCESSORS ==================== -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = to_json_schema_process(def.element, ctx, { - ...params, - path: [...params.path, "items"], - }); -}; -// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an -// absent key, but their declared input type stays required. An input JSON Schema describes the -// declared type, so resolve past them to the schema that actually carries the optionality. -// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see -// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". -function inputOptin(schema) { - const def = schema._zod.def; - if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { - return inputOptin(def.out); - } - if (def.type === "catch") { - return inputOptin(def.innerType); - } - return schema._zod.optin; -} -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const shape = def.shape; - // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires - const symbolKeys = Object.getOwnPropertySymbols(shape); - if (symbolKeys.length && - handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { - return; - } - json.type = "object"; - json.properties = {}; - for (const key in shape) { - // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into - assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - })); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const field = def.shape[key]; - if (ctx.io === "input") { - return inputOptin(field) === undefined; - } - else { - return field._zod.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = to_json_schema_process(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = to_json_schema_process(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = to_json_schema_process(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; - // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. - ctx.intersections.push(allOf); -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? to_json_schema_process(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - let minItems = def.items.length; - while (minItems > 0) { - const item = def.items[minItems - 1]; - const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; - if (!optional) - break; - minItems--; - } - const maxItems = def.items.length; - const isClosed = !def.rest; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (isClosed) { - json.items = false; - } - else if (rest) { - json.items = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else { - json.items = prefixItems; - if (isClosed) { - json.additionalItems = false; - } - else if (rest) { - json.additionalItems = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - // explicit user-defined length checks take precedence - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the - * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key - * behind a wrapper only carries its own `type` before then, and a union key only has its branches. - * - * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather - * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this - * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` - * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema - * outright. */ -function stringifyKeyNames(bySchema, json, visited) { - // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. - if (json.$ref) { - // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again - if (visited.has(json)) - return json; - visited.add(json); - const def = bySchema.get(json)?.def; - if (!def) - return json; - const inlined = stringifyKeyNames(bySchema, def, visited); - return inlined === def ? json : inlined; - } - for (const keyword of ["anyOf", "oneOf"]) { - const branches = json[keyword]; - if (!Array.isArray(branches)) - continue; - const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); - // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` - if (mapped.some((branch, i) => branch !== branches[i])) - json = { ...json, [keyword]: mapped }; - } - // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric - const types = Array.isArray(json.type) ? json.type : [json.type]; - const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); - // a heterogeneous key carries no type at all, so its numeric members are caught here instead - const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); - if (!numericType && !values?.some((v) => typeof v === "number")) - return json; - const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; - if (rest.enum) - rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); - else if (typeof rest.const === "number") - rest.const = String(rest.const); - // a heterogeneous key keeps its absent type: the stringified members already say what a key may be - if (!numericType) - return rest; - rest.type = "string"; - if (!values) - rest.pattern = (types.includes("number") ? number : integer).source; - return rest; -} -/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ -const pendingRecords = new WeakMap(); -function rewriteKeyNames(ctx) { - // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. - const bySchema = new Map(); - for (const entry of ctx.seen.values()) { - if (entry.def && !bySchema.has(entry.schema)) - bySchema.set(entry.schema, entry); - } - const rewrites = new Map(); - for (const record of pendingRecords.get(ctx) ?? []) { - const seen = ctx.seen.get(record); - const names = (seen?.def ?? seen?.schema)?.propertyNames; - if (!names || names === true || rewrites.has(names)) - continue; - const rewritten = stringifyKeyNames(bySchema, names, new Set()); - if (rewritten !== names) - rewrites.set(names, rewritten); - } - if (!rewrites.size) - return; - // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together - for (const entry of ctx.seen.values()) { - for (const carrier of [entry.schema, entry.def]) { - const rewritten = carrier && rewrites.get(carrier.propertyNames); - if (rewritten) - carrier.propertyNames = rewritten; - } - } -} -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - // Use patternProperties for looseRecord with regex patterns - const valueSchema = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"], - }); - json.patternProperties = {}; - for (const pattern of patterns) { - assignProp(json.patternProperties, pattern.source, valueSchema); - } - } - else { - // Default behavior: use propertyNames + additionalProperties - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = to_json_schema_process(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - let pending = pendingRecords.get(ctx); - if (!pending) { - pending = []; - pendingRecords.set(ctx, pending); - ctx.deferred.push(() => rewriteKeyNames(ctx)); - } - pending.push(schema); - } - json.additionalProperties = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - // Add required for keys with discrete values (enum, literal, etc.) - const keyValues = keyType._zod.values; - // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. - const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; - if (keyValues && !def.partial && !omittableOnInput) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json.required = validKeyValues.map(String); - } - } -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. - * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other - * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ -const UNREPRESENTABLE_DEFAULT = Symbol(); -function serializeDefaultValue(value, schema, ctx, json, params) { - let unrepresentable = false; - const serialized = JSON.stringify(value, (_, val) => { - if (typeof val !== "bigint") - return val; - unrepresentable = true; - return null; - }); - if (!unrepresentable) - return JSON.parse(serialized); - handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); - return UNREPRESENTABLE_DEFAULT; -} -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json.default = value; -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io !== "input") - return; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json._prefault = value; -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); - return; - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -// ==================== ALL PROCESSORS ==================== -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - // Registry case - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - // First pass: process all schemas to build the seen map - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - to_json_schema_process(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - // Update the context with external configuration - ctx.external = external; - // Second pass: emit each schema - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - assignProp(schemas, key, finalize(ctx, schema)); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - // Single schema case - const ctx = initializeContext({ ...params, processors: allProcessors }); - to_json_schema_process(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - - -const en_error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - mac: "MAC address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - credit_card: "credit card number", - jwt: "JWT", - template_literal: "input", - }; - // type names: missing keys = do not translate (use raw value via ?? fallback) - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN", - // All other type names omitted - they fall back to raw values via ?? operator - }; - function getTypeName(type, input) { - if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { - return String(input); - } - return TypeDictionary[type] ?? type; - } - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = getTypeName(issue.expected); - const receivedType = parsedType(issue.input); - const received = getTypeName(receivedType, issue.input); - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { - const opts = issue.options.map((o) => `'${o}'`).join(" | "); - return `Invalid discriminator value. Expected ${opts}`; - } - if (issue.inclusive === false) { - return "Invalid input: more than one option matched"; - } - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -/* export default */ function en() { - return { - localeError: en_error(), - }; -} - - - - -/* Prototypes that already carry the lazy helper methods. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -/* Helper methods live as non-enumerable lazy getters on the shared - * prototype instead of own properties on every instance. On first - * access the getter allocates the per-instance closure and caches it - * as a non-enumerable own property, so detached usage still works and - * the allocation only happens for methods actually touched. */ -function _lazyMethod(proto, key, make) { - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const value = make(this); - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - }, - }); -} -const classic_errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - const proto = Object.getPrototypeOf(inst); - if (_installedErrorProtos.has(proto)) - return; - _installedErrorProtos.add(proto); - _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); - _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); - _lazyMethod(proto, "addIssue", (self) => (issue) => { - self.issues.push(issue); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - _lazyMethod(proto, "addIssues", (self) => (issues) => { - self.issues.push(...issues); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - Object.defineProperty(proto, "isEmpty", { - configurable: true, - enumerable: false, - get() { - return this.issues.length === 0; - }, - }); -}; -const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); -const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - - - -const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); -const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); - -// Codec functions -const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); -const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); -const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); -const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); -const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - - - - - - - - -// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. -function _ensureDefaultLocale() { - if (!globalConfig.localeError) - core_config(en()); -} -// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first -function _ensureDefaultMemoizer() { - if (!globalConfig.memoizer) - core_config({ memoizer: memoizer() }); -} -const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - _ensureDefaultLocale(); - $ZodType.init(inst, def); - inst.def = def; - inst.type = def.type; - return inst; -}, { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return schemas_optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return schemas_optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return schemas_array(this); - }, - or(arg) { - return schemas_union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return schemas_default(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return schemas_catch(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(undefined).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn, ...args) { - return args.length === 0 ? fn(this) : fn(this, ...args); - }, - // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. - get "~standard"() { - return hide(this, "~standard", { - ...standardProps(this), - jsonSchema: { - input: createStandardJSONSchemaMethod(this, "input"), - output: createStandardJSONSchemaMethod(this, "output"), - }, - }); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, - parse: function _parse(data, params) { - return classic_parse_parse(this, data, params, { callee: _parse }); - }, - parseAsync: async function _parseAsync(data, params) { - return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); - }, - safeParse(data, params) { - return parse_safeParse(this, data, params); - }, - async safeParseAsync(data, params) { - return parse_safeParseAsync(this, data, params); - }, - // `spa` is an alias: same function object as `safeParseAsync`, as before. - get spa() { - return this?.safeParseAsync; - }, - set spa(value) { - util_own(this, "spa", value); - }, - encode: function _encode(data, params) { - return classic_parse_encode(this, data, params, { callee: _encode }); - }, - decode: function _decode(data, params) { - return classic_parse_decode(this, data, params, { callee: _decode }); - }, - encodeAsync: async function _encodeAsync(data, params) { - return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); - }, - decodeAsync: async function _decodeAsync(data, params) { - return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); - }, - safeEncode(data, params) { - return parse_safeEncode(this, data, params); - }, - safeDecode(data, params) { - return parse_safeDecode(this, data, params); - }, - async safeEncodeAsync(data, params) { - return parse_safeEncodeAsync(this, data, params); - }, - async safeDecodeAsync(data, params) { - return parse_safeDecodeAsync(this, data, params); - }, - toJSONSchema(params) { - return createToJSONSchemaMethod(this, {})(params); - }, - // Reads through to the registry on every access, so it must not cache. - get description() { - return globalRegistry.get(this)?.description; - }, - // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. - get _def() { - return this._zod.def; - }, -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; -}, { - regex(...args) { - return this.check(_regex(...args)); - }, - includes(...args) { - return this.check(_includes(...args)); - }, - startsWith(...args) { - return this.check(_startsWith(...args)); - }, - endsWith(...args) { - return this.check(_endsWith(...args)); - }, - min(...args) { - return this.check(_minLength(...args)); - }, - max(...args) { - return this.check(_maxLength(...args)); - }, - length(...args) { - return this.check(_length(...args)); - }, - nonempty(...args) { - return this.check(_minLength(1, ...args)); - }, - lowercase(params) { - return this.check(_lowercase(params)); - }, - uppercase(params) { - return this.check(_uppercase(params)); - }, - trim() { - return this.check(_trim()); - }, - normalize(...args) { - return this.check(_normalize(...args)); - }, - toLowerCase() { - return this.check(_toLowerCase()); - }, - toUpperCase() { - return this.check(_toUpperCase()); - }, - slugify() { - return this.check(_slugify()); - }, -}); -const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); -}, { - email(params) { - return this.check(_email(ZodEmail, params)); - }, - url(params) { - return this.check(_url(ZodURL, params)); - }, - jwt(params) { - return this.check(_jwt(ZodJWT, params)); - }, - emoji(params) { - return this.check(api_emoji(ZodEmoji, params)); - }, - guid(params) { - return this.check(_guid(ZodGUID, params)); - }, - uuid(params) { - return this.check(_uuid(ZodUUID, params)); - }, - uuidv4(params) { - return this.check(_uuidv4(ZodUUID, params)); - }, - uuidv6(params) { - return this.check(_uuidv6(ZodUUID, params)); - }, - uuidv7(params) { - return this.check(_uuidv7(ZodUUID, params)); - }, - nanoid(params) { - return this.check(_nanoid(ZodNanoID, params)); - }, - cuid(params) { - return this.check(_cuid(ZodCUID, params)); - }, - cuid2(params) { - return this.check(_cuid2(ZodCUID2, params)); - }, - ulid(params) { - return this.check(_ulid(ZodULID, params)); - }, - base64(params) { - return this.check(_base64(ZodBase64, params)); - }, - base64url(params) { - return this.check(_base64url(ZodBase64URL, params)); - }, - xid(params) { - return this.check(_xid(ZodXID, params)); - }, - ksuid(params) { - return this.check(_ksuid(ZodKSUID, params)); - }, - ipv4(params) { - return this.check(_ipv4(ZodIPv4, params)); - }, - ipv6(params) { - return this.check(_ipv6(ZodIPv6, params)); - }, - cidrv4(params) { - return this.check(_cidrv4(ZodCIDRv4, params)); - }, - cidrv6(params) { - return this.check(_cidrv6(ZodCIDRv6, params)); - }, - e164(params) { - return this.check(_e164(ZodE164, params)); - }, - datetime(params) { - return this.check(_isoDateTime(ZodISODateTime, params)); - }, - date(params) { - return this.check(_isoDate(ZodISODate, params)); - }, - time(params) { - return this.check(_isoTime(schemas_ZodISOTime, params)); - }, - duration(params) { - return this.check(_isoDuration(schemas_ZodISODuration, params)); - }, -}); -function schemas_string(params) { - return _string(ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_guid(params) { - return core._guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_uuid(params) { - return core._uuid(ZodUUID, params); -} -function uuidv4(params) { - return core._uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return core._uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function uuidv7(params) { - return core._uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return core._url(ZodURL, { - protocol: core.regexes.httpProtocol, - hostname: core.regexes.domain, - ...util.normalizeParams(params), - }); -} -const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_emoji(params) { - return core._emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_nanoid(params) { - return core._nanoid(ZodNanoID, params); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** - * Validates a CUID v1 string. - * - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. - * See https://github.com/paralleldrive/cuid. - */ -function schemas_cuid(params) { - return core._cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid2(params) { - return core._cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ulid(params) { - return core._ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_xid(params) { - return core._xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ksuid(params) { - return core._ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv4(params) { - return core._ipv4(ZodIPv4, params); -} -const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_mac(params) { - return core._mac(ZodMAC, params); -} -const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv6(params) { - return core._ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv4(params) { - return core._cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv6(params) { - return core._cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64(params) { - return core._base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64url(params) { - return core._base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_e164(params) { - return core._e164(ZodE164, params); -} -const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { - core.$ZodCreditCard.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_creditCard(params) { - return core._creditCard(ZodCreditCard, params); -} -const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return core._jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function stringFormat(format, fnOrRegex, _params = {}) { - return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function schemas_hostname(_params) { - return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); -} -function schemas_hex(_params) { - return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); -} -function schemas_hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = core.regexes[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return core._stringFormat(ZodCustomStringFormat, format, regex, params); -} -const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}, { - gt(value, params) { - return this.check(_gt(value, params)); - }, - gte(value, params) { - return this.check(_gte(value, params)); - }, - min(value, params) { - return this.check(_gte(value, params)); - }, - lt(value, params) { - return this.check(_lt(value, params)); - }, - lte(value, params) { - return this.check(_lte(value, params)); - }, - max(value, params) { - return this.check(_lte(value, params)); - }, - int(params) { - return this.check(schemas_int(params)); - }, - safe(params) { - return this.check(schemas_int(params)); - }, - positive(params) { - return this.check(_gt(0, params)); - }, - nonnegative(params) { - return this.check(_gte(0, params)); - }, - negative(params) { - return this.check(_lt(0, params)); - }, - nonpositive(params) { - return this.check(_lte(0, params)); - }, - multipleOf(value, params) { - return this.check(_multipleOf(value, params)); - }, - step(value, params) { - return this.check(_multipleOf(value, params)); - }, - finite() { - return this; - }, -}); -function schemas_number(params) { - return _number(ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function schemas_int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return core._float32(ZodNumberFormat, params); -} -function float64(params) { - return core._float64(ZodNumberFormat, params); -} -function int32(params) { - return core._int32(ZodNumberFormat, params); -} -function uint32(params) { - return core._uint32(ZodNumberFormat, params); -} -const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function schemas_boolean(params) { - return _boolean(ZodBoolean, params); -} -const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { - core.$ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}, { - gte(value, params) { - return this.check(checks.gte(value, params)); - }, - min(value, params) { - return this.check(checks.gte(value, params)); - }, - gt(value, params) { - return this.check(checks.gt(value, params)); - }, - lt(value, params) { - return this.check(checks.lt(value, params)); - }, - lte(value, params) { - return this.check(checks.lte(value, params)); - }, - max(value, params) { - return this.check(checks.lte(value, params)); - }, - positive(params) { - return this.check(checks.gt(BigInt(0), params)); - }, - negative(params) { - return this.check(checks.lt(BigInt(0), params)); - }, - nonpositive(params) { - return this.check(checks.lte(BigInt(0), params)); - }, - nonnegative(params) { - return this.check(checks.gte(BigInt(0), params)); - }, - multipleOf(value, params) { - return this.check(checks.multipleOf(value, params)); - }, -}))); -function schemas_bigint(params) { - return core._bigint(ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { - core.$ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); -}))); -function int64(params) { - return core._int64(ZodBigIntFormat, params); -} -function uint64(params) { - return core._uint64(ZodBigIntFormat, params); -} -const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { - core.$ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); -}))); -function symbol(params) { - return core._symbol(ZodSymbol, params); -} -const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { - core.$ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); -}))); -function schemas_undefined(params) { - return core._undefined(ZodUndefined, params); -} - -const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function schemas_null(params) { - return api_null(ZodNull, params); -} - -const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); -}); -function any() { - return _any(ZodAny); -} -const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); -}); -function unknown() { - return _unknown(ZodUnknown); -} -const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return _never(ZodNever, params); -} -const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { - core.$ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); -}))); -function schemas_void(params) { - return core._void(ZodVoid, params); -} - -const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { - core.$ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}))); -function schemas_date(params) { - return core._date(ZodDate, params); -} -const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; -}, { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - }, -}); -function schemas_array(element, params) { - return _array(ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return schemas_enum(Object.keys(shape)); -} -const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); -}, { - keyof() { - return schemas_enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall: catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: undefined }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - exactPartial(...args) { - return partial(ZodExactOptional, this, args[0], "exactPartial"); - }, - required(...args) { - return util_required(ZodNonOptional, this, args[0]); - }, -}); -function schemas_object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util.normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function schemas_union(options, params) { - return new ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - core.$ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}))); -/** Creates an exclusive union (XOR) where exactly one option must match. - * Unlike regular unions that succeed when any option matches, xor fails if - * zero or more than one option matches the input. */ -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new ZodDiscriminatedUnion({ - type: "union", - options: options, - discriminator, - ...normalizeParams(params), - }); -} -const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); -}, { - rest(rest) { - return this.clone({ - ...this._zod.def, - rest: rest, - }); - }, - partial() { - const def = this._zod.def; - // a refinement was authored against the full arity; partialing would run it on a shorter array - if (def.checks?.length) - throw new Error(".partial() cannot be used on tuple schemas containing refinements"); - return this.clone({ - ...def, - items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), - }); - }, -}))); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof core.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items: items, - rest, - ...util.normalizeParams(params), - }); -} -const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function schemas_record(keyType, valueType, params) { - // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() - if (!valueType || !valueType._zod) { - return new ZodRecord({ - type: "record", - keyType: schemas_string(), - valueType: keyType, - ...normalizeParams(valueType), - }); - } - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...util.normalizeParams(params), - partial: true, - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...util.normalizeParams(params), - }); -} -const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_set(valueType, params) { - return new ZodSet({ - type: "set", - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { - core.$ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); - inst.min = (size, params) => inst.check(core._minSize(size, params)); - inst.max = (size, params) => inst.check(core._maxSize(size, params)); - inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); -}))); -function schemas_file(params) { - return core._file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = inst); - // _issue.continue ??= true; - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function schemas_optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return schemas_optional(nullable(innerType)); -} -const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { - core.$ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), - }); -} - -const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { - core.$ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); -}))); -function nan(params) { - return core._nan(ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - core.$ZodCodec.init(inst, def); -}))); -function schemas_codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -function invertCodec(codec) { - const def = codec._zod.def; - return new ZodCodec({ - type: "pipe", - in: def.out, - out: def.in, - transform: def.reverseTransform, - reverseTransform: def.transform, - }); -} -const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { - ZodPipe.init(inst, def); - $ZodPreprocess.init(inst, def); -}); -const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { - core.$ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); -}))); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { - core.$ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function schemas_promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { - core.$ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); -}))); -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), - output: params?.output ?? unknown(), - }); -} - -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -// custom checks -function schemas_check(fn) { - const ch = new core.$ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return core._custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn, params) { - return _superRefine(fn, params); -} -// Re-export describe and meta from core -const schemas_describe = describe; -const schemas_meta = api_meta; -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util.normalizeParams(params), - }); - inst._zod.bag.Class = cls; - // Override check to emit invalid_type instead of custom - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...(inst._zod.def.path ?? [])], - }); - } - }; - return inst; -} - -// stringbool -const stringbool = (...args) => core._stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString, -}, ...args); -function schemas_json(params) { - const jsonSchema = lazy(() => { - return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -function preprocess(fn, schema) { - return new ZodPreprocess({ - type: "pipe", - in: transform(fn), - out: schema, - }); -} - - - - -function iso_datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -function iso_date(params) { - return _isoDate(ZodISODate, params); -} -function iso_time(params) { - return core._isoTime(ZodISOTime, params); -} -function iso_duration(params) { - return core._isoDuration(ZodISODuration, params); -} - -// Zod 3 compat layer - -/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ -const ZodIssueCode = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom", -}; - -/** @deprecated Use `z.config(params)` instead. */ -function setErrorMap(map) { - core.config({ - customError: map, - }); -} -/** @deprecated Use `z.config()` instead. */ -function getErrorMap() { - return core.config().customError; -} -/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ -var compat_ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); - - - -function coerce_string(params) { - return core._coercedString(schemas.ZodString, params); -} -function coerce_number(params) { - return _coercedNumber(ZodNumber, params); -} -function coerce_boolean(params) { - return core._coercedBoolean(schemas.ZodBoolean, params); -} -function coerce_bigint(params) { - return core._coercedBigint(schemas.ZodBigInt, params); -} -function coerce_date(params) { - return core._coercedDate(schemas.ZodDate, params); -} - - - -//#region src/constants.ts -const LATEST_PROTOCOL_VERSION = "2025-11-25"; -const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-06-18", - "2025-03-26", - "2024-11-05", - "2024-10-07" -]; -/** -* `_meta` key associating a message with a 2025-11-25 task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; -/** -* `_meta` key carrying the MCP protocol version governing a request. -* -* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. -*/ -const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; -/** -* `_meta` key identifying the client software making a request. -* -* Clients SHOULD include it on every request; the value is self-reported and -* intended for display, logging, and debugging — servers should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; -/** -* `_meta` key identifying the server software producing a response. -* -* Servers SHOULD include it on every response; the value is self-reported and -* intended for display, logging, and debugging — clients should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; -/** -* `_meta` key carrying the client's capabilities for a request. -* -* Capabilities are declared per request rather than once at initialization; -* servers must not infer capabilities from prior requests. -*/ -const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; -/** -* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request -* that opened the stream a notification was delivered on. -* -* Stamped by the server on every notification delivered via a -* `subscriptions/listen` stream (including the leading -* `notifications/subscriptions/acknowledged`); on stdio, where all messages -* share one channel, clients use it to correlate notifications with their -* originating subscription. The value is the listen request's JSON-RPC ID -* verbatim. -*/ -const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; -/** -* `_meta` key carrying the desired log level for a request. -* -* When absent, the server must not send `notifications/message` notifications -* for the request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. -*/ -const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; -/** -* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `traceparent` header format, -* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. -* -* @see https://www.w3.org/TR/trace-context/#traceparent-header -*/ -const TRACEPARENT_META_KEY = "traceparent"; -/** -* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `tracestate` header format, -* e.g. `vendor1=value1,vendor2=value2`. -* -* @see https://www.w3.org/TR/trace-context/#tracestate-header -*/ -const TRACESTATE_META_KEY = "tracestate"; -/** -* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C Baggage header format, -* e.g. `userId=alice,serverRegion=us-east-1`. -* -* @see https://www.w3.org/TR/baggage/ -*/ -const BAGGAGE_META_KEY = "baggage"; -const JSONRPC_VERSION = "2.0"; -const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); -const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); -const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); -const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); -const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); - -//#endregion -//#region src/schemas.ts -const JSONValueSchema = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema), - schemas_array(JSONValueSchema) -])); -const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); -const JSONArraySchema = schemas_array(JSONValueSchema); -/** -* A progress token, used to associate progress notifications with the original request. -*/ -const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* An opaque token used to represent a cursor for pagination. -*/ -const CursorSchema = schemas_string(); -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); -/** -* Metadata for associating messages with a task. -* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); -const RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -/** -* Common params for any request. -*/ -const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -/** -* Common params for any task-augmented request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); -const RequestSchema = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -const NotificationSchema = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema.loose().optional() -}); -/** -* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). -* Loose — implementation-specific keys pass through. -* -* The serverInfo key identifies the server software producing the response -* (servers SHOULD include it on every response; the value is self-reported -* and intended for display, logging, and debugging). The getter defers the -* `ImplementationSchema` reference, which is declared later in this file. -*/ -const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { - return ImplementationSchema.optional().catch(void 0); -} }); -const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); -/** -* A uniquely identifying ID for a request in JSON-RPC. -*/ -const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* A request that expects a response. -*/ -const JSONRPCRequestSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}).strict(); -/** -* A notification which does not expect a response. -*/ -const JSONRPCNotificationSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}).strict(); -/** -* A successful (non-error) response to a request. -*/ -const JSONRPCResultResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -/** -* A response to a request that indicates an error occurred. -*/ -const JSONRPCErrorResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: schemas_object({ - code: schemas_number().int(), - message: schemas_string(), - data: unknown().optional() - }) -}).strict(); -const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -/** -* A response that indicates success but carries no data. -*/ -const EmptyResultSchema = ResultSchema.strict(); -const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: schemas_string().optional() -}); -/** -* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. -* -* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. -* -* This notification indicates that the result will be unused, so any associated processing SHOULD cease. -* -* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. -*/ -const CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema -}); -/** -* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. -*/ -const IconSchema = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() -}); -/** -* Base schema to add `icons` property. -* -*/ -const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); -/** -* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. -*/ -const BaseMetadataSchema = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() -}); -/** -* Describes the name and version of an MCP implementation. -*/ -const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() -}); -const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); -const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; -}, intersection(schemas_object({ - form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() -}), JSONObjectSchema.optional())); -/** -* Task capabilities for clients, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ClientTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() - }).optional() -}); -/** -* Task capabilities for servers, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ServerTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() -}); -/** -* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. -*/ -const ClientCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - sampling: schemas_object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }).optional(), - elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** -* This request is sent from the client to the server when it first connects, asking it to begin initialization. -*/ -const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema -}); -/** -* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. -*/ -const ServerCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -/** -* After receiving an initialize request from the client, the server sends this response. -*/ -const InitializeResultSchema = ResultSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: schemas_string().optional() -}); -/** -* This notification is sent from the client to the server after initialization has finished. -*/ -const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() -}); -/** -* A request from the client asking the server to advertise its supported protocol -* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers -* MUST implement `server/discover`. Clients MAY call it but are not required to — -* version negotiation can also happen inline via the per-request `_meta` envelope. -*/ -const DiscoverRequestSchema = RequestSchema.extend({ - method: literal("server/discover"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The result returned by the server for a `server/discover` request. -*/ -const DiscoverResultSchema = ResultSchema.extend({ - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilitiesSchema, - instructions: schemas_string().optional() -}); -/** -* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. -*/ -const PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() -}); -const ProgressSchema = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) -}); -const ProgressNotificationParamsSchema = schemas_object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); -/** -* An out-of-band notification used to inform the receiver of a progress update for a long-running request. -* -* @category notifications/progress -*/ -const ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema -}); -const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); -const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); -const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); -/** -* The contents of a specific resource or sub-resource. -*/ -const ResourceContentsSchema = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); -/** -* A Zod schema for validating Base64 strings that is more performant and -* robust for very large inputs than the default regex-based check. It avoids -* stack overflows by using the native `atob` function for validation. -*/ -const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } -}, { message: "Invalid Base64 string" }); -const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); -/** -* The sender or recipient of messages and data in a conversation. -*/ -const RoleSchema = schemas_enum(["user", "assistant"]); -/** -* Optional annotations providing clients additional context about a resource. -*/ -const AnnotationsSchema = schemas_object({ - audience: schemas_array(RoleSchema).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() -}); -/** -* A known resource that the server is capable of reading. -*/ -const ResourceSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* A template description for resources available on the server. -*/ -const ResourceTemplateSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of resources the server has. -*/ -const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); -/** -* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. -*/ -const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); -/** -* Sent from the client to request a list of resource templates the server has. -*/ -const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); -/** -* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. -*/ -const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); -const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); -/** -* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. -*/ -const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to the server, to read a specific resource URI. -*/ -const ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema -}); -/** -* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. -*/ -const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); -/** -* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() -}); -const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. -*/ -const SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema -}); -const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema -}); -/** -* The set of notification types a client opts in to on a `subscriptions/listen` -* request. Each type is opt-in; the server MUST NOT send a notification type -* the client has not explicitly requested here. -*/ -const SubscriptionFilterSchema = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() -}); -const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent from the client to open a long-lived channel for receiving notifications -* outside the context of a specific request (protocol revision 2026-07-28). -* Replaces the previous HTTP GET endpoint and `resources/subscribe`. -*/ -const SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: literal("subscriptions/listen"), - params: SubscriptionsListenRequestParamsSchema -}); -const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent by the server as the first message on a `subscriptions/listen` stream -* to acknowledge that the subscription has been established and report which -* notification types it agreed to honor (protocol revision 2026-07-28). -*/ -const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/subscriptions/acknowledged"), - params: SubscriptionsAcknowledgedNotificationParamsSchema -}); -/** -* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's -* JSON-RPC ID under the canonical subscription-id key (mirroring the same key -* on every notification delivered on the stream). Extends -* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed -* here too. -*/ -const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); -/** -* The response to a `subscriptions/listen` request, signalling that the -* subscription has ended gracefully (for example, during server shutdown). -* Because the listen stream is long-lived, this result is sent only when the -* server tears the subscription down; an abrupt transport close carries no -* response. The result body is otherwise empty. -*/ -const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); -/** -* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. -*/ -const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); -/** -* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema -}); -/** -* Describes an argument that a prompt can accept. -*/ -const PromptArgumentSchema = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) -}); -/** -* A prompt or prompt template that the server offers. -*/ -const PromptSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema)), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of prompts and prompt templates the server has. -*/ -const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); -/** -* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. -*/ -const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); -/** -* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. -*/ -const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() -}); -/** -* Used by the client to get a prompt provided by the server. -*/ -const GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema -}); -/** -* Text provided to or from an LLM. -*/ -const TextContentSchema = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* An image provided to or from an LLM. -*/ -const ImageContentSchema = schemas_object({ - type: literal("image"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Audio content provided to or from an LLM. -*/ -const AudioContentSchema = schemas_object({ - type: literal("audio"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A tool call request from an assistant (LLM). -* Represents the assistant's request to use a tool. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolUseContentSchema = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* The contents of a resource, embedded into a prompt or tool call result. -*/ -const EmbeddedResourceSchema = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A resource that the server is capable of reading, included in a prompt or tool call result. -* -* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. -*/ -const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); -/** -* A content block that can be used in prompts and tool results. -*/ -const ContentBlockSchema = schemas_union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** -* Describes a message returned as part of a prompt. -*/ -const PromptMessageSchema = schemas_object({ - role: RoleSchema, - content: ContentBlockSchema -}); -/** -* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. -*/ -const GetPromptResultSchema = ResultSchema.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema) -}); -/** -* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Additional properties describing a `Tool` to clients. -* -* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. -* They are not guaranteed to provide a faithful description of -* tool behavior (including descriptive properties like `title`). -* -* Clients should never make tool use decisions based on `ToolAnnotations` -* received from untrusted servers. -*/ -const ToolAnnotationsSchema = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() -}); -/** -* Execution-related properties for a tool. -*/ -const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" -]).optional() }); -/** -* Definition for a tool the client can call. -*/ -const ToolSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the client to request a list of tools the server has. -*/ -const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); -/** -* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. -*/ -const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); -/** -* The server's response to a tool call. -*/ -const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ - content: schemas_array(ContentBlockSchema).default([]), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() -}); -/** -* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. -*/ -const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); -/** -* Parameters for a `tools/call` request. -*/ -const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Used by the client to invoke a tool provided by the server. -*/ -const CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema -}); -/** -* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Base schema for list changed subscription options (without callback). -* Used internally for Zod validation of `autoRefresh` and `debounceMs`. -*/ -const ListChangedOptionsBaseSchema = schemas_object({ - autoRefresh: schemas_boolean().default(true), - debounceMs: schemas_number().int().nonnegative().default(300) -}); -/** -* The severity of a log message. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingLevelSchema = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" -]); -/** -* Parameters for a `logging/setLevel` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); -/** -* A request from the client to the server, to enable or adjust logging. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema -}); -/** -* Parameters for a `notifications/message` notification. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: schemas_string().optional(), - data: unknown() -}); -/** -* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema -}); -/** -* Hints to use for model selection. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); -/** -* The server's preferences for model selection, requested of the client during sampling. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelPreferencesSchema = schemas_object({ - hints: schemas_array(ModelHintSchema).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() -}); -/** -* Controls tool usage behavior in sampling requests. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" -]).optional() }); -/** -* The result of a tool execution, provided by the user (server). -* Represents the outcome of invoking a tool requested via `ToolUseContent`. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolResultContentSchema = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Basic content types for sampling responses (without tool use). -* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingContentSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema -]); -/** -* Content block types allowed in sampling messages. -* This includes text, image, audio, tool use requests, and tool results. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** -* Describes a message issued to or received from an LLM API. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageSchema = schemas_object({ - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Parameters for a `sampling/createMessage` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - messages: schemas_array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema.optional(), - tools: schemas_array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); -/** -* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema -}); -/** -* The client's response to a `sampling/create_message` request from the server. -* This is the backwards-compatible version that returns single content (no arrays). -* Used when the request does not include tools. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema, - content: SamplingContentSchema -}); -/** -* The client's response to a `sampling/create_message` request when tools were provided. -* This version supports array content for tool use flows. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) -}); -/** -* Primitive schema definition for boolean fields. -*/ -const BooleanSchemaSchema = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() -}); -/** -* Primitive schema definition for string fields. -*/ -const StringSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() -}); -/** -* Primitive schema definition for number fields. -*/ -const NumberSchemaSchema = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() -}); -/** -* Schema for single-selection enumeration without display titles for options. -*/ -const UntitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() -}); -/** -* Schema for single-selection enumeration with display titles for each option. -*/ -const TitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() -}); -/** -* Use {@linkcode TitledSingleSelectEnumSchema} instead. -* This interface will be removed in a future version. -*/ -const LegacyTitledEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() -}); -const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** -* Schema for multiple-selection enumeration without display titles for options. -*/ -const UntitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Schema for multiple-selection enumeration with display titles for each option. -*/ -const TitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Combined schema for multiple-selection enumeration -*/ -const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** -* Primitive schema definition for enum fields. -*/ -const EnumSchemaSchema = schemas_union([ - LegacyTitledEnumSchemaSchema, - SingleSelectEnumSchemaSchema, - MultiSelectEnumSchemaSchema -]); -/** -* Union of all primitive schema definitions. -*/ -const PrimitiveSchemaDefinitionSchema = schemas_union([ - EnumSchemaSchema, - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema -]); -/** -* Parameters for an `elicitation/create` request for form-based elicitation. -*/ -const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) -}); -/** -* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. -*/ -const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() -}); -/** -* The parameters for a request to elicit additional information from the user via the client. -*/ -const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** -* A request from the server to elicit user input via the client. -* The client should present the message and form fields to the user (form mode) -* or navigate to a URL (URL mode). -*/ -const ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema -}); -/** -* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); -/** -* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema -}); -/** -* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. -*/ -const ElicitResultSchema = ResultSchema.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) -}); -/** -* A reference to a resource or resource template definition. -*/ -const ResourceTemplateReferenceSchema = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() -}); -/** -* Identifies a prompt. -*/ -const PromptReferenceSchema = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() -}); -/** -* Parameters for a {@linkcode CompleteRequest | completion/complete} request. -*/ -const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() -}); -/** -* A request from the client to the server, to ask for completion options. -*/ -const CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema -}); -/** -* The server's response to a {@linkcode CompleteRequest | completion/complete} request -*/ -const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) -}) }); -/** -* Represents a root directory or file that the server can operate on. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootSchema = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the server to request a list of root URIs from the client. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The client's response to a `roots/list` request from the server. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); -/** -* A notification from the client to the server, informing it that the list of roots has changed. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Task creation parameters, used to ask that the server create a task to represent a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskCreationParamsSchema = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() -}); -/** -* The status of a task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusSchema = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" -]); -/** -* A pollable state object associated with a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskSchema = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) -}); -/** -* Result returned when a task is created, containing the task data wrapped in a `task` field. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); -/** -* Parameters for task status notification. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -/** -* A notification sent when a task's status changes. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema -}); -/** -* A request to get the state of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode GetTaskRequest | tasks/get} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -/** -* A request to get the result of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a `tasks/result` request. -* The structure matches the result type of the original request. -* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. -* -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadResultSchema = ResultSchema.loose(); -/** -* A request to list tasks. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); -/** -* The response to a {@linkcode ListTasksRequest | tasks/list} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); -/** -* A request to cancel a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -const ClientRequestSchema = schemas_union([ - PingRequestSchema, - auth_CUe6YdwF_InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -const ClientNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - auth_CUe6YdwF_InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -const ClientResultSchema = schemas_union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema -]); -const ServerRequestSchema = schemas_union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema -]); -const ServerNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema -]); -const ServerResultSchema = schemas_union([ - EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - auth_CUe6YdwF_CallToolResultSchema, - ListToolsResultSchema, - SubscriptionsListenResultSchema -]); - -//#endregion -//#region src/auth.ts -/** -* Reusable URL validation that disallows `javascript:` scheme -*/ -const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: "URL must be parseable", - fatal: true - }); - return NEVER; - } -}).refine((url) => { - const u = new URL(url); - return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; -}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); -/** -* RFC 9728 OAuth Protected Resource Metadata -*/ -const OAuthProtectedResourceMetadataSchema = looseObject({ - resource: schemas_string().url(), - authorization_servers: schemas_array(SafeUrlSchema).optional(), - jwks_uri: schemas_string().url().optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - bearer_methods_supported: schemas_array(schemas_string()).optional(), - resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - resource_name: schemas_string().optional(), - resource_documentation: schemas_string().optional(), - resource_policy_uri: schemas_string().url().optional(), - resource_tos_uri: schemas_string().url().optional(), - tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), - authorization_details_types_supported: schemas_array(schemas_string()).optional(), - dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - dpop_bound_access_tokens_required: schemas_boolean().optional() -}); -/** -* RFC 8414 OAuth 2.0 Authorization Server Metadata -*/ -const OAuthMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint: schemas_string().optional(), - introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - code_challenge_methods_supported: schemas_array(schemas_string()).optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery 1.0 Provider Metadata -* -* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata -*/ -const OpenIdProviderMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - acr_values_supported: schemas_array(schemas_string()).optional(), - subject_types_supported: schemas_array(schemas_string()), - id_token_signing_alg_values_supported: schemas_array(schemas_string()), - id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - display_values_supported: schemas_array(schemas_string()).optional(), - claim_types_supported: schemas_array(schemas_string()).optional(), - claims_supported: schemas_array(schemas_string()).optional(), - service_documentation: schemas_string().optional(), - claims_locales_supported: schemas_array(schemas_string()).optional(), - ui_locales_supported: schemas_array(schemas_string()).optional(), - claims_parameter_supported: schemas_boolean().optional(), - request_parameter_supported: schemas_boolean().optional(), - request_uri_parameter_supported: schemas_boolean().optional(), - require_request_uri_registration: schemas_boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery metadata that may include OAuth 2.0 fields -* This schema represents the real-world scenario where OIDC providers -* return a mix of OpenID Connect and OAuth 2.0 metadata fields -*/ -const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape -}); -/** -* OAuth 2.1 token response -*/ -const OAuthTokensSchema = schemas_object({ - access_token: schemas_string(), - id_token: schemas_string().optional(), - token_type: schemas_string(), - expires_in: coerce_number().optional(), - scope: schemas_string().optional(), - refresh_token: schemas_string().optional() -}).strip(); -/** -* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. -* -* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when -* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, -* so strict checking rejects conformant IdPs. -*/ -const IdJagTokenExchangeResponseSchema = schemas_object({ - issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), - access_token: schemas_string(), - token_type: schemas_string().optional(), - expires_in: schemas_number().optional(), - scope: schemas_string().optional() -}).strip(); -/** -* OAuth 2.1 error response -*/ -const OAuthErrorResponseSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional(), - error_uri: schemas_string().optional() -}); -/** -* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` -*/ -const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata -*/ -const OAuthClientMetadataSchema = schemas_object({ - redirect_uris: schemas_array(SafeUrlSchema), - token_endpoint_auth_method: schemas_string().optional(), - grant_types: schemas_array(schemas_string()).optional(), - response_types: schemas_array(schemas_string()).optional(), - application_type: schemas_string().optional(), - client_name: schemas_string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: schemas_string().optional(), - contacts: schemas_array(schemas_string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: schemas_string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: any().optional(), - software_id: schemas_string().optional(), - software_version: schemas_string().optional(), - software_statement: schemas_string().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration client information -*/ -const OAuthClientInformationSchema = schemas_object({ - client_id: schemas_string(), - client_secret: schemas_string().optional(), - client_id_issued_at: schemas_number().optional(), - client_secret_expires_at: schemas_number().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) -*/ -const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration error response -*/ -const OAuthClientRegistrationErrorSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional() -}).strip(); -/** -* RFC 7009 OAuth 2.0 Token Revocation request -*/ -const OAuthTokenRevocationRequestSchema = schemas_object({ - token: schemas_string(), - token_type_hint: schemas_string().optional() -}).strip(); - -//#endregion - -//# sourceMappingURL=auth-CUe6YdwF.mjs.map - - - - - - - - -//#region ../core-internal/src/errors/crossBundleBrand.ts -/** -* Cross-bundle `instanceof` support for the SDK error classes. -* -* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their -* own copy of `core-internal`, so an error constructed by one package fails a -* prototype-identity `instanceof` against the same class re-exported by the other — -* exactly the check a dual-role process (gateway, host, in-process test) writes. -* -* Instead of prototype identity, branded classes stamp every instance with the brand -* strings of its class chain under a registry symbol (`Symbol.for`, shared across -* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the -* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior -* is unchanged for anything unbranded. -* -* A class participates by defining an **own** `mcpBrand` static (via a `static {}` -* block, so nothing reaches the declaration files — a declared `protected static` -* field would make the constructor types nominally incompatible across the bundled -* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as -* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand -* keep plain prototype semantics — a foreign base-class instance never satisfies -* `instanceof UserSubclass`. -* -* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core -* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), -* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios -* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a -* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 -* (Symbol.hasInstance on every schema class for cross-version interop). -* -* Contract notes: -* - Participation criterion: **every error class exported from a public package that -* callers are documented to `instanceof` must be branded.** The per-package -* errorBrandConformance tests walk the export surfaces and fail naming any -* exported Error subclass that has not opted in. -* - Brands assert **identity, not shape**: brand strings are version-less, so an -* instance from one SDK version matches the class of another. Members added to a -* branded class in a later version may be absent on a matched instance — read -* fields defensively, and treat branded classes as additive-only. The escape -* hatch when a release must break a branded class's read contract: change that -* class's brand string in the same release, which cleanly severs cross-version -* matching for that class. The per-package brand pins make the rename -* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each -* package's errorBrandConformance test pins its package-local ones. -* - Cross-bundle matching requires **both** copies to be at or after the release -* that introduced branding; against an older copy, behavior degrades to plain -* prototype `instanceof` in both directions. -* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would -* break the brand statics; default esbuild/webpack/terser settings do not. -*/ -/** Registry symbol — identical across bundled copies and realms. */ -const BRANDS = Symbol.for("mcp.sdk.errorBrands"); -/** -* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an -* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — -* subclasses inherit the stamping without touching their constructors. -* -* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would -* satisfy `instanceof` while lacking the prototype members (getters like `.status`) -* that callers reach for after the check. -*/ -function stampErrorBrands(instance, ctor) { - const brands = /* @__PURE__ */ new Set(); - let current = ctor; - while (typeof current === "function") { - const brand = current.mcpBrand; - if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); - current = Object.getPrototypeOf(current); - } - if (brands.size === 0) return; - Object.defineProperty(instance, BRANDS, { - value: brands, - enumerable: false, - configurable: true - }); -} -/** -* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the -* value carries the **own** brand of the class being tested against (cross-bundle -* path), falling back to ordinary prototype-based `instanceof` otherwise. -*/ -function brandedHasInstance(cls, value) { - try { - if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { - const carried = value[BRANDS]; - if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; - } - } catch {} - return Function.prototype[Symbol.hasInstance].call(cls, value); -} - -//#endregion -//#region ../core-internal/src/auth/errors.ts -/** -* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} -* and extensions. -*/ -let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { - /** - * The request is missing a required parameter, includes an invalid parameter value, - * includes a parameter more than once, or is otherwise malformed. - */ - OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; - /** - * Client authentication failed (e.g., unknown client, no client authentication included, - * or unsupported authentication method). - */ - OAuthErrorCode$1["InvalidClient"] = "invalid_client"; - /** - * The provided authorization grant or refresh token is invalid, expired, revoked, - * does not match the redirection URI used in the authorization request, or was issued to another client. - */ - OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; - /** - * The authenticated client is not authorized to use this authorization grant type. - */ - OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; - /** - * The authorization grant type is not supported by the authorization server. - */ - OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; - /** - * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. - */ - OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; - /** - * The resource owner or authorization server denied the request. - */ - OAuthErrorCode$1["AccessDenied"] = "access_denied"; - /** - * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. - */ - OAuthErrorCode$1["ServerError"] = "server_error"; - /** - * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. - */ - OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; - /** - * The authorization server does not support obtaining an authorization code using this method. - */ - OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; - /** - * The authorization server does not support the requested token type. - */ - OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; - /** - * The access token provided is expired, revoked, malformed, or invalid for other reasons. - */ - OAuthErrorCode$1["InvalidToken"] = "invalid_token"; - /** - * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) - */ - OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; - /** - * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) - */ - OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; - /** - * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) - */ - OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; - /** - * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) - */ - OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; - /** - * The request requires higher privileges than provided by the access token. - */ - OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; - /** - * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) - */ - OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; - return OAuthErrorCode$1; -}({}))); -/** -* OAuth error class for all OAuth-related errors. -*/ -var src_CX2iR2pK_OAuthError = class OAuthError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, errorUri) { - super(message); - this.code = code; - this.errorUri = errorUri; - this.name = "OAuthError"; - stampErrorBrands(this, new.target); - } - /** - * Converts the error to a standard OAuth error response object. - */ - toResponseObject() { - const response = { - error: this.code, - error_description: this.message - }; - if (this.errorUri) response.error_uri = this.errorUri; - return response; - } - /** - * Creates an {@linkcode OAuthError} from an OAuth error response. - */ - static fromResponse(response) { - return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); - } -}; - -//#endregion -//#region ../core-internal/src/errors/sdkErrors.ts -/** -* Error codes for SDK errors (local errors that never cross the wire). -* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses -* descriptive string values for better developer experience. -* -* These errors are thrown locally by the SDK and are never serialized as -* JSON-RPC error responses. -*/ -let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { - /** Transport is not connected */ - SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; - /** Transport is already connected */ - SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; - /** Protocol is not initialized */ - SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; - /** Required capability is not supported by the remote side */ - SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; - /** Request timed out waiting for response */ - SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; - /** Connection was closed */ - SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; - /** Failed to send message */ - SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; - /** Response result failed local schema validation */ - SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; - /** - * The response carried a `resultType` discriminator (protocol revision - * 2026-07-28) naming a result kind this client cannot consume yet, e.g. - * `input_required`. The kind is carried in `data.resultType`. - */ - SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; - /** - * The multi-round-trip auto-fulfilment driver exhausted its round cap - * (`inputRequired.maxRounds`) without the server returning a complete - * result. `data.rounds` carries the cap that was hit and - * `data.lastResult` carries the last `input_required` payload received - * (`{ inputRequests, requestState? }`), so callers can inspect or resume - * the flow manually. - */ - SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; - /** - * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / - * `listResources()` / `listResourceTemplates()` walk hit the - * `ClientOptions.listMaxPages` cap without the server's pagination - * converging. `data.method` carries the list verb and - * `data.listMaxPages` the cap that was hit; raise the cap or fall back to - * explicit per-page `{ cursor }` calls. - */ - SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; - /** - * The spec method being sent does not exist on the negotiated protocol - * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or - * `server/discover` toward a 2025-era peer). Raised locally, before - * anything reaches the transport. The method and era are carried in - * `data.method` / `data.era`. - */ - SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; - /** - * Protocol-era negotiation at connect time failed without producing either a - * usable modern (2026-07-28+) era or a definitive legacy fallback signal — - * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a - * network failure, or the server answered the probe with a 5xx (a typed - * connect error, never an era verdict). - * - * Negotiation-phase only: this code is never used once an era is - * established. Auth walls never carry it: a 401/403 rejecting the probe - * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} - * instead, so era-recovery flows keyed on this code (e.g. cached-verdict - * gateways) can never persist a verdict for an unauthorized exchange. - */ - SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; - SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; - /** - * HTTP 401 authentication failure: the transport's re-auth retry still got - * 401 (`Server returned 401 after re-authentication`), or the version - * negotiation probe was rejected 401 with no `authProvider` configured - * (`Version negotiation failed: the server requires authorization (HTTP 401)`). - * Carried on an {@linkcode SdkHttpError} with `status: 401`. - */ - SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; - /** - * HTTP 403 denial: the step-up re-authorization retry limit was reached, - * or the version negotiation probe was rejected 403 - * (`Version negotiation failed: the server denied access (HTTP 403)`). - * Carried on an {@linkcode SdkHttpError} with `status: 403`. - */ - SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; - SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; - SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; - SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; - return SdkErrorCode$1; -}({}); -/** -* SDK errors are local errors that never cross the wire. -* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors -* that are serialized and sent as error responses. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" -* try { -* // Throwing an SDK error -* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); -* } catch (error) { -* // Checking error type by code -* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { -* // Handle timeout -* } -* } -* ``` -*/ -var src_CX2iR2pK_SdkError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "SdkError"; - stampErrorBrands(this, new.target); - } -}; -/** -* An {@linkcode SdkError} subclass for HTTP transport failures. -* -* Thrown by the streamable HTTP transport when the server responds with a -* non-OK status code. Narrows {@linkcode SdkError.data | data} to -* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status -* without unsafe casting. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" -* if (error instanceof SdkHttpError) { -* console.log(error.status); // number -* console.log(error.statusText); // string | undefined -* } -* ``` -*/ -var SdkHttpError = class extends src_CX2iR2pK_SdkError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); - } - constructor(code, message, data) { - super(code, message, data); - this.name = "SdkHttpError"; - } - get status() { - return this.data.status; - } - get statusText() { - return this.data.statusText; - } -}; - -//#endregion -//#region ../core-internal/src/shared/authUtils.ts -/** -* Utilities for handling OAuth resource URIs. -*/ -/** -* Converts a server URL to a resource URL by removing the fragment. -* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} -* states that resource URIs "MUST NOT include a fragment component". -* Keeps everything else unchanged (scheme, domain, port, path, query). -*/ -function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); - resourceURL.hash = ""; - return resourceURL; -} -/** -* Checks if a requested resource URL matches a configured resource URL. -* A requested resource matches if it has the same scheme, domain, port, -* and its path starts with the configured resource's path. -* -* @param options - The options object -* @param options.requestedResource - The resource URL being requested -* @param options.configuredResource - The resource URL that has been configured -* @returns true if the requested resource matches the configured resource, false otherwise -*/ -function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); - if (requested.origin !== configured.origin) return false; - if (requested.pathname.length < configured.pathname.length) return false; - const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; - const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; - return requestedPath.startsWith(configuredPath); -} - -//#endregion -//#region ../core-internal/src/shared/clientCapabilityRequirements.ts -/** -* Inbound request methods whose processing structurally requires a client -* capability, keyed by method, valued by the capabilities required. -* -* Currently empty: none of the request methods served on the 2026-07-28 -* registry unconditionally requires a client capability. Entries appear here -* when such methods exist — for example requests whose handling embeds -* elicitation or sampling input requests (the input-request engine), or -* opt-in subscription delivery. Handler-conditional requirements (a specific -* tool that needs sampling) are not expressible as a static method table and -* are enforced at the point the requirement arises instead. -*/ -const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); -/** -* The client capabilities a request method structurally requires, or -* `undefined` when the method has no static requirement. -*/ -function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { - return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; -} -function isPlainObject$7(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Whether a required nested member counts as declared even though it is not -* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at -* all) is read as form support — the pre-mode (2025) meaning of a bare -* declaration — so an `elicitation.form` requirement treats it as satisfied. -* Declaring any mode explicitly (for example `elicitation: { url: {} }`) -* removes the implication. -*/ -function isImpliedCapabilityMember(capability, member, declaredValue) { - return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; -} -/** -* The client capabilities an embedded multi-round-trip input request requires -* (call site 2 — the outbound input-request leg): a server MUST NOT send an -* `inputRequests` kind the request's declared client capabilities do not -* cover. Returns `undefined` for entries whose method is not one of the -* embedded input-request kinds (those are a server bug handled separately, -* not a capability question). -* -* The requirement is mode-aware where the capability is: URL-mode elicitation -* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires -* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a -* mode the client did not declare); sampling with `tools`/`toolChoice` -* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies -* the form requirement — see {@linkcode missingClientCapabilities}. -*/ -function requiredClientCapabilitiesForInputRequest(entry) { - switch (entry.method) { - case "elicitation/create": - if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; - return { elicitation: { form: {} } }; - case "sampling/createMessage": { - const params = entry.params; - if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; - return { sampling: {} }; - } - case "roots/list": return { roots: {} }; - default: return; - } -} -/** -* Computes the subset of `required` client capabilities the client did not -* declare. Returns `undefined` when every required capability is declared; -* otherwise returns an object in the `ClientCapabilities` shape containing -* exactly the missing capabilities (suitable for -* `data.requiredCapabilities` on the `-32021` error). -* -* A capability counts as declared when its top-level key is present on the -* declared capabilities; when the requirement names nested members (for -* example `elicitation: { url: {} }`), each named member must also be present -* under the declared capability. One lenient reading applies: a bare -* `elicitation: {}` declaration (no mode sub-capability at all) counts as -* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare -* declaration. An absent or empty `declared` value means -* nothing is declared — every required capability is missing (the structural -* clean-refusal posture for sessions with no per-request capability view). -*/ -function src_CX2iR2pK_missingClientCapabilities(required, declared) { - const missing = {}; - for (const [capability, requirement] of Object.entries(required)) { - if (requirement === void 0) continue; - const declaredValue = declared === void 0 ? void 0 : declared[capability]; - if (declaredValue === void 0) { - missing[capability] = requirement; - continue; - } - if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { - const missingMembers = {}; - for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; - if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; - } - } - return Object.keys(missing).length > 0 ? missing : void 0; -} - -//#endregion -//#region ../core-internal/src/shared/protocolEras.ts -/** -* The first protocol revision of the modern (2026-07-28) era. Revision identifiers -* are ISO dates, so lexicographic comparison orders them chronologically. -*/ -const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; -/** -* Modern-era protocol revisions this SDK can negotiate via `server/discover`. -* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy -* `initialize` list), so adding a revision here can never leak a modern version -* string into a 2025-era handshake. Internal — not part of the public API surface. -*/ -const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); -/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ -function isModernProtocolVersion(version) { - return version >= FIRST_MODERN_PROTOCOL_VERSION; -} -/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ -function legacyProtocolVersions(versions) { - return versions.filter((version) => !isModernProtocolVersion(version)); -} -/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ -function modernProtocolVersions(versions) { - return versions.filter((version) => isModernProtocolVersion(version)); -} - -//#endregion -//#region ../core-internal/src/wire/textFallback.ts -/** -* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH -* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` -* is a non-object value (array/primitive/`null`) and the handler authored no -* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. -* Object-shaped (or absent) `structuredContent` returns the same reference. -* -* Leaf module: imported by both era codec modules, so it must NOT import from -* `./codec.js` (which value-imports the rev codecs at top level — that would -* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec -* module first). -*/ -function appendTextFallbackForNonObject(result) { - const sc = result.structuredContent; - if (sc === void 0) return result; - if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; - if (result.content?.some((c) => c.type === "text") ?? false) return result; - return { - ...result, - content: [...result.content ?? [], { - type: "text", - text: JSON.stringify(sc) - }] - }; -} - -//#endregion -//#region ../core-internal/src/wire/resultFamilies.ts -/** -* Result-family keys that must never default into a `{content: []}` tools/call -* success. Shared by the 2025 wire-seam schema and server normalization. -* Leaf module (like `textFallback.ts`): imported by registry/server paths, so -* it must NOT import from `./codec.js` — that would close a runtime cycle. -*/ -const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ - "task", - "inputRequests", - "requestState" -]; -/** -* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and -* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. -*/ -function normalizeContentlessToolResult(value) { - if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; - return { - ...value, - content: [] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts -/** -* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from -* the public/neutral types/schemas.ts. The neutral layer is the public-API -* superset and is free to evolve (e.g., SEP-2106 widening); this file is the -* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. -* -* This is the era's complete frozen wire-parse contract — both the 2025-only -* delta (the deprecated task family, the era role unions) AND frozen copies of -* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, -* prompts/resources/completion/elicitation, …). The 2026-era codec -* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. -* -* The 2025-only delta (the task message surface, restored types-only by #2248 -* for interop with task-capable 2025 peers) is parsed ONLY through this era's -* registry; the deprecated Task* schemas also live (marked `@deprecated`) in -* the neutral schema layer so the public types stay nameable without a -* cross-layer import — nameability is constant, runtime availability is -* version-keyed — but appear in no API signature. Q1 increment 2 — deletions -* are physical: the -* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do -* carry the deprecated Task* sub-schemas by composition — soft contamination, -* tracked for anchor-exactness adjudication). -* -* The only cross-layer dependency is `import type { JSONObject, JSONValue }` -* from the neutral types barrel — pure structural type aliases with no parse -* behavior. No runtime schema is shared with the neutral layer. -*/ -function build$1() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - /** - * Common params for any request. - */ - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** - * Common params for any task-augmented request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const RequestSchema$1 = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema$1.loose().optional() - }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * A response that indicates success but carries no data. - */ - const EmptyResultSchema$1 = ResultSchema$1.strict(); - const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - requestId: RequestIdSchema$1.optional(), - reason: schemas_string().optional() - }); - /** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. - */ - const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - /** - * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. - */ - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - /** - * Base schema to add `icons` property. - * - */ - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - /** - * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. - */ - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - /** - * Describes the name and version of an MCP implementation. - */ - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** - * Task capabilities for clients, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** - * Task capabilities for servers, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - /** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema$1, - clientInfo: ImplementationSchema$1 - }); - /** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ - const InitializeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema$1 - }); - /** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - /** - * After receiving an initialize request from the client, the server sends this response. - */ - const InitializeResultSchema$1 = ResultSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema$1, - serverInfo: ImplementationSchema$1, - instructions: schemas_string().optional() - }); - /** - * This notification is sent from the client to the server after initialization has finished. - */ - const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ - const PingRequestSchema$1 = RequestSchema$1.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema$1.optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - /** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); - const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); - const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); - /** - * The contents of a specific resource or sub-resource. - */ - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * Optional annotations providing clients additional context about a resource. - */ - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - /** - * A known resource that the server is capable of reading. - */ - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * A template description for resources available on the server. - */ - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of resources the server has. - */ - const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); - /** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ - const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); - /** - * Sent from the client to request a list of resource templates the server has. - */ - const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); - /** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ - const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); - const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); - /** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ - const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to the server, to read a specific resource URI. - */ - const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ - const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); - /** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ - const SubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema$1 - }); - const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - /** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - /** - * Describes an argument that a prompt can accept. - */ - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - /** - * A prompt or prompt template that the server offers. - */ - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ - const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); - /** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ - const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); - /** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ - const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }); - /** - * Used by the client to get a prompt provided by the server. - */ - const GetPromptRequestSchema$1 = RequestSchema$1.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema$1 - }); - /** - * Text provided to or from an LLM. - */ - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * An image provided to or from an LLM. - */ - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Audio content provided to or from an LLM. - */ - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * The contents of a resource, embedded into a prompt or tool call result. - */ - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. - */ - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - /** - * A content block that can be used in prompts and tool results. - */ - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - /** - * Describes a message returned as part of a prompt. - */ - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - /** - * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. - */ - const GetPromptResultSchema$1 = ResultSchema$1.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - /** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Additional properties describing a `Tool` to clients. - * - * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on `ToolAnnotations` - * received from untrusted servers. - */ - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - /** - * Execution-related properties for a tool. - */ - const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - /** - * Definition for a tool the client can call. - */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the client to request a list of tools the server has. - */ - const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); - /** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ - const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); - /** - * The server's response to a tool call. - */ - const CallToolResultSchema$1 = ResultSchema$1.extend({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_record(schemas_string(), unknown()).optional(), - isError: schemas_boolean().optional() - }); - /** - * Parameters for a `tools/call` request. - */ - const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Used by the client to invoke a tool provided by the server. - */ - const CallToolRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema$1 - }); - /** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * The severity of a log message. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * Parameters for a `logging/setLevel` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); - /** - * A request from the client to the server, to enable or adjust logging. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestSchema$1 = RequestSchema$1.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema$1 - }); - /** - * Parameters for a `notifications/message` notification. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - /** - * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - /** - * Hints to use for model selection. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - /** - * The server's preferences for model selection, requested of the client during sampling. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - /** - * Controls tool usage behavior in sampling requests. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - /** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via `ToolUseContent`. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_object({}).loose().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingContentSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1 - ]); - /** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** - * Describes a message issued to or received from an LLM API. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Parameters for a `sampling/createMessage` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request from the server. - * This is the backwards-compatible version that returns single content (no arrays). - * Used when the request does not include tools. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema$1, - content: SamplingContentSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request when tools were provided. - * This version supports array content for tool use flows. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) - }); - /** - * Primitive schema definition for boolean fields. - */ - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - /** - * Primitive schema definition for string fields. - */ - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - /** - * Primitive schema definition for number fields. - */ - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - /** - * Schema for single-selection enumeration without display titles for options. - */ - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - /** - * Schema for single-selection enumeration with display titles for each option. - */ - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - /** - * Use {@linkcode TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - */ - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - /** - * Schema for multiple-selection enumeration without display titles for options. - */ - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Schema for multiple-selection enumeration with display titles for each option. - */ - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Combined schema for multiple-selection enumeration - */ - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - /** - * Primitive schema definition for enum fields. - */ - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - /** - * Union of all primitive schema definitions. - */ - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - /** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - /** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ - const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() - }); - /** - * The parameters for a request to elicit additional information from the user via the client. - */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ - const ElicitRequestSchema$1 = RequestSchema$1.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); - /** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema$1 - }); - /** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ - const ElicitResultSchema$1 = ResultSchema$1.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) - }); - /** - * A reference to a resource or resource template definition. - */ - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - /** - * Identifies a prompt. - */ - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - /** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ - const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }); - /** - * A request from the client to the server, to ask for completion options. - */ - const CompleteRequestSchema$1 = RequestSchema$1.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode CompleteRequest | completion/complete} request - */ - const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) - }) }); - /** - * Represents a root directory or file that the server can operate on. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the server to request a list of root URIs from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsRequestSchema$1 = RequestSchema$1.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema$1.optional() - }); - /** - * The client's response to a `roots/list` request from the server. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); - /** - * A notification from the client to the server, informing it that the list of roots has changed. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Task creation parameters, used to ask that the server create a task to represent a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskCreationParamsSchema$1 = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() - }); - /** - * The status of a task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusSchema$1 = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - /** - * A pollable state object associated with a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskSchema$1 = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema$1, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) - }); - /** - * Result returned when a task is created, containing the task data wrapped in a `task` field. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); - /** - * Parameters for task status notification. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); - /** - * A notification sent when a task's status changes. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema$1 - }); - /** - * A request to get the state of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a {@linkcode GetTaskRequest | tasks/get} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); - /** - * A request to get the result of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a `tasks/result` request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. - * - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); - /** - * A request to list tasks. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); - /** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); - /** - * A request to cancel a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - RequestSchema: RequestSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - ResultSchema: ResultSchema$1, - RequestIdSchema: RequestIdSchema$1, - EmptyResultSchema: EmptyResultSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, - InitializeRequestSchema: InitializeRequestSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - InitializeResultSchema: InitializeResultSchema$1, - InitializedNotificationSchema: InitializedNotificationSchema$1, - PingRequestSchema: PingRequestSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, - PaginatedRequestSchema: PaginatedRequestSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - RoleSchema: RoleSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, - ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, - SubscribeRequestSchema: SubscribeRequestSchema$1, - UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, - UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolExecutionSchema: ToolExecutionSchema$1, - ToolSchema: ToolSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, - CallToolRequestSchema: CallToolRequestSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, - SetLevelRequestSchema: SetLevelRequestSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingContentSchema: SamplingContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, - ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - RootSchema: RootSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, - TaskCreationParamsSchema: TaskCreationParamsSchema$1, - TaskStatusSchema: TaskStatusSchema$1, - TaskSchema: TaskSchema$1, - CreateTaskResultSchema: CreateTaskResultSchema$1, - TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, - TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, - GetTaskRequestSchema: GetTaskRequestSchema$1, - GetTaskResultSchema: GetTaskResultSchema$1, - GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, - GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, - ListTasksRequestSchema: ListTasksRequestSchema$1, - ListTasksResultSchema: ListTasksResultSchema$1, - CancelTaskRequestSchema: CancelTaskRequestSchema$1, - CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), - ClientRequestSchema: schemas_union([ - PingRequestSchema$1, - InitializeRequestSchema$1, - CompleteRequestSchema$1, - SetLevelRequestSchema$1, - GetPromptRequestSchema$1, - ListPromptsRequestSchema$1, - ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema$1, - SubscribeRequestSchema$1, - UnsubscribeRequestSchema$1, - CallToolRequestSchema$1, - ListToolsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ClientNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - InitializedNotificationSchema$1, - RootsListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1 - ]), - ClientResultSchema: schemas_union([ - EmptyResultSchema$1, - CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema$1, - ElicitResultSchema$1, - ListRootsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - ServerRequestSchema: schemas_union([ - PingRequestSchema$1, - CreateMessageRequestSchema$1, - ElicitRequestSchema$1, - ListRootsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ServerNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - LoggingMessageNotificationSchema$1, - ResourceUpdatedNotificationSchema$1, - ResourceListChangedNotificationSchema$1, - ToolListChangedNotificationSchema$1, - PromptListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1, - ElicitationCompleteNotificationSchema$1 - ]), - ServerResultSchema: schemas_union([ - EmptyResultSchema$1, - InitializeResultSchema$1, - CompleteResultSchema$1, - GetPromptResultSchema$1, - ListPromptsResultSchema$1, - ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema$1, - CallToolResultSchema$1, - ListToolsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - CallToolResultWireSchema: unknown().superRefine((value, ctx) => { - if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; - for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { - ctx.addIssue({ - code: "custom", - message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` - }); - return; - } - }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) - }; -} -let memo$1; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2025() { - return memo$1 ??= build$1(); -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts -/** -* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). -* -* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON -* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, -* so when an era-blind handler advertises a non-object root, the 2025 codec's -* `encodeResult('tools/list', …)` projects it down to -* `{type:'object', properties:{result:}, required:['result']}`, and -* `projectCallToolResult` wraps the matching `structuredContent` as -* `{result:}`. The 2026 codec's projections are the identity. -* -* These helpers are wire-layer property — they exist so the projection can -* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} -* and never be re-derived in shared/ or server-side code. -*/ -/** -* Whether a JSON Schema's root is non-object: either an explicit non-object -* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless -* roots that the schema-conversion layer can prove are objects are stamped -* `type:'object'` upstream, so they reach this predicate as object roots. -*/ -function isNonObjectJsonSchemaRoot(json) { - return json["type"] !== "object"; -} -/** -* Keyword-position keys whose values are instance data (not subschemas). A -* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to -* rewrite. Only consulted when the current object is in keyword position — -* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name -* position whose value IS a subschema and is recursed into. -*/ -const REF_REWRITE_DATA_POSITION_KEYS = new Set([ - "const", - "enum", - "default", - "examples" -]); -/** -* Keyword-position keys whose value is a name→subschema map. Entries inside -* such a map are in NAME position: their keys are author-chosen property -* names (which may collide with JSON Schema keywords), their values are -* subschemas to recurse into. -*/ -const REF_REWRITE_NAME_MAP_KEYS = new Set([ - "properties", - "patternProperties", - "$defs", - "definitions", - "dependentSchemas", - "dependencies" -]); -/** -* Whether a subtree's `$id` establishes a new resolution base. A fragment-only -* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not -* change the RFC 3986 base URI — same-document pointers inside still resolve -* against the document root and must be rewritten. -*/ -function establishesNewBase(id) { - return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); -} -/** -* Wrap a non-object output schema in the 2025-era envelope: -* `{type:'object', properties:{result:}, required:['result']}`. -* -* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema -* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) -* are rewritten to account for the new `#/properties/result` root: bare `#` → -* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs -* (anything not starting with `#`) are left untouched. -* -* The rewrite is position-aware: data-valued keywords -* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended -* into; the same names appearing as property names under -* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ -* `dependencies` ARE descended into (they're subschemas). The rewrite is also -* `$id`-scoped: if the natural root carries a base-establishing `$id` no -* pointer is rewritten (same-document refs inside resolve against the embedded -* `$id` base, not the wrapper root), and any subtree that establishes its own -* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, -* draft-07's anchor spelling) does not establish a base and IS descended into. -*/ -function wrapOutputSchemaForLegacy(natural) { - const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; - if (establishesNewBase(natural["$id"])) return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: natural }, - required: ["result"] - }; - const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; - const rewriteRefs = (node, parentIsNameMap) => { - if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); - if (node === null || typeof node !== "object") return node; - if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; - const out = {}; - let convertedRecursion = false; - for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); - else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; - else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; - else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; - else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); - else out[k] = rewriteRefs(v, false); - if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; - else out["$ref"] = "#/properties/result"; - return out; - }; - return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: rewriteRefs(natural, false) }, - required: ["result"] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/registry.ts -const requestMethodKeys$1 = { - ping: null, - initialize: null, - "completion/complete": null, - "logging/setLevel": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "resources/subscribe": null, - "resources/unsubscribe": null, - "tools/call": null, - "tools/list": null, - "tasks/get": null, - "tasks/result": null, - "tasks/list": null, - "tasks/cancel": null, - "sampling/createMessage": null, - "elicitation/create": null, - "roots/list": null -}; -const notificationMethodKeys$1 = { - "notifications/cancelled": null, - "notifications/progress": null, - "notifications/initialized": null, - "notifications/roots/list_changed": null, - "notifications/tasks/status": null, - "notifications/message": null, - "notifications/resources/updated": null, - "notifications/resources/list_changed": null, - "notifications/tools/list_changed": null, - "notifications/prompts/list_changed": null, - "notifications/elicitation/complete": null -}; -const resultMethodKeys = { - ping: null, - initialize: null, - "completion/complete": null, - "logging/setLevel": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "resources/subscribe": null, - "resources/unsubscribe": null, - "tools/call": null, - "tools/list": null, - "sampling/createMessage": null, - "elicitation/create": null, - "roots/list": null -}; -let maps$1; -function registryMaps() { - if (maps$1) return maps$1; - const s = buildSchemas2025(); - maps$1 = { - requestSchemas: { - ping: s.PingRequestSchema, - initialize: s.InitializeRequestSchema, - "completion/complete": s.CompleteRequestSchema, - "logging/setLevel": s.SetLevelRequestSchema, - "prompts/get": s.GetPromptRequestSchema, - "prompts/list": s.ListPromptsRequestSchema, - "resources/list": s.ListResourcesRequestSchema, - "resources/templates/list": s.ListResourceTemplatesRequestSchema, - "resources/read": s.ReadResourceRequestSchema, - "resources/subscribe": s.SubscribeRequestSchema, - "resources/unsubscribe": s.UnsubscribeRequestSchema, - "tools/call": s.CallToolRequestSchema, - "tools/list": s.ListToolsRequestSchema, - "tasks/get": s.GetTaskRequestSchema, - "tasks/result": s.GetTaskPayloadRequestSchema, - "tasks/list": s.ListTasksRequestSchema, - "tasks/cancel": s.CancelTaskRequestSchema, - "sampling/createMessage": s.CreateMessageRequestSchema, - "elicitation/create": s.ElicitRequestSchema, - "roots/list": s.ListRootsRequestSchema - }, - notificationSchemas: { - "notifications/cancelled": s.CancelledNotificationSchema, - "notifications/progress": s.ProgressNotificationSchema, - "notifications/initialized": s.InitializedNotificationSchema, - "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, - "notifications/tasks/status": s.TaskStatusNotificationSchema, - "notifications/message": s.LoggingMessageNotificationSchema, - "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, - "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, - "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, - "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, - "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema - }, - resultSchemas: { - ping: s.EmptyResultSchema, - initialize: s.InitializeResultSchema, - "completion/complete": s.CompleteResultSchema, - "logging/setLevel": s.EmptyResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "resources/subscribe": s.EmptyResultSchema, - "resources/unsubscribe": s.EmptyResultSchema, - "tools/call": s.CallToolResultWireSchema, - "tools/list": s.ListToolsResultSchema, - "sampling/createMessage": s.CreateMessageResultWithToolsSchema, - "elicitation/create": s.ElicitResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps$1; -} -/** -* Forces the lazy registry maps (and, through them, the era's schema memo). -* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmRegistryMaps2025() { - registryMaps(); -} -/** The 2025-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2025(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); -} -/** The 2025-era notification-method set. */ -function hasNotificationMethod2025(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); -} -/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ -function hasResultMethod(method) { - return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); -} -function getResultSchema(method) { - return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; -} -function getRequestSchema(method) { - return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; -} -function getNotificationSchema(method) { - return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2025RequestMethods = Object.keys(requestMethodKeys$1); -const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/codec.ts -function isPlainObject$6(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState$1(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA$1 = { - ok: false, - reason: "not-in-era" -}; -/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ -function toolNeedsLegacyWrap(t) { - return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); -} -/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ -function toNeutralResult(value) { - return value; -} -const rev2025Codec = { - era: "2025-11-25", - hasRequestMethod: hasRequestMethod2025, - hasNotificationMethod: hasNotificationMethod2025, - validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), - validateResult: (method, raw) => triState$1(getResultSchema(method), raw), - validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), - hasInputRequestMethod: () => false, - validateInputRequest: () => NOT_IN_ERA$1, - validateInputResponse: () => NOT_IN_ERA$1, - samplingResultVariant: ((hasTools, raw) => { - const s = buildSchemas2025(); - return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); - }), - outboundEnvelope: (_material) => void 0, - validateEnvelopeMeta: (_meta) => [], - projectCallToolResult(result, advertisedOutputSchema) { - const withText = appendTextFallbackForNonObject(result); - const sc = withText.structuredContent; - if (sc === void 0) return withText; - const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); - const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); - if (!valueIsNonObject && !schemaWrapped) return withText; - return { - ...withText, - structuredContent: { result: sc } - }; - }, - decodeResult(_method, raw) { - if (isPlainObject$6(raw) && "resultType" in raw) { - const stripped = { ...raw }; - delete stripped["resultType"]; - return { - kind: "complete", - result: toNeutralResult(stripped) - }; - } - return { - kind: "complete", - result: toNeutralResult(raw) - }; - }, - encodeResult(method, result) { - if (method !== "tools/list") return result; - const tools = result.tools; - if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; - return { - ...result, - tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { - ...t, - outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) - } : t) - }; - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope: (_material) => void 0 -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts -/** -* 2026-era wire schemas (protocol revision 2026-07-28). -* -* Fully self-contained — no runtime imports from types/schemas.ts. The -* neutral types/schemas.ts layer is the public-API superset and is free to -* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN -* against the 2026-07-28 anchor. Every era-shared building block (content -* blocks, resources, prompts, capabilities, notifications, …) that the wire -* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at -* the point this revision was sealed, dependencies first. The only cross-layer -* dependency is `import type { JSONObject, JSONValue }` from the neutral types -* barrel — pure structural type aliases with no parse behavior. -* -* This module is the only place the per-request `_meta` envelope is modeled. -* The envelope is wire-only vocabulary: the protocol layer lifts it off -* inbound requests before any handler runs and surfaces it at -* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at -* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc -* deferral ("enforced per request at dispatch time, not here") is now -* discharged by that codec step. -* -* No 2025-era traffic ever touches this module, so requiredness here is -* bare and spec-exact (the shared-schema `.catch` hazards do not apply). -* -* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed -* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the -* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from -* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result -* body to the new `ResultMetaObject` key -* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). -* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is -* modeled anywhere (per ruling: the final revision is the only 2026-07-28). -*/ -function build() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * The severity of a log message. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; - const ClientCapabilities2026Schema = schemas_object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions - }); - const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; - const ServerCapabilities2026Schema = schemas_object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions - }); - /** - * The per-request `_meta` envelope carried by every request under protocol revision - * 2026-07-28: the protocol version governing the request, the client implementation - * info, and the client's capabilities — declared per request rather than once at - * initialization — plus the optional log-level opt-in. - * - * This schema models the complete envelope on its own (loose: foreign keys - * pass through - the lift extracts exactly the reserved keys, so enforcement - * never sees extension material). Requiredness is enforced per request at - * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. - */ - const RequestMetaEnvelopeSchema = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() - }); - /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: looseObject({ - $schema: schemas_string().optional(), - type: literal("object") - }), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string(), - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era sampling content union (composes the forked tool-result shape). */ - const SamplingMessageContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** 2026-era SamplingMessage (anchor-exact: single block or array). */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** Open union per the anchor: 'complete' | 'input_required' | string. */ - const ResultTypeSchema = schemas_string(); - /** - * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): - * loose, with the serverInfo key typed when present; the outbound stamp - * is the encode contract's `stampServerInfoMeta` step. - */ - const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); - const wireMeta = ResultMetaSchema.optional(); - function wireResult(shape) { - return looseObject({ - _meta: wireMeta, - resultType: ResultTypeSchema.default("complete"), - ...shape - }); - } - const ResultSchema$1 = wireResult({}); - const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); - const CallToolResultSchema$1 = wireResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }); - const ListToolsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const GetPromptResultSchema$1 = wireResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - const ListResourcesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListResourceTemplatesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ReadResourceResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }); - const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }); - /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ - const CacheableResultSchema = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]) - }); - const DiscoverResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }); - /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ - const CreateMessageRequestParamsSchema$1 = schemas_object({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** 2026-era embedded sampling request (de-JSON-RPC'd). */ - const CreateMessageRequestSchema$1 = schemas_object({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input - * requests do NOT carry the per-request `_meta` envelope on this revision — - * the anchor declares a bare optional `_meta` on `params`. - */ - const ListRootsRequestSchema$1 = schemas_object({ - method: literal("roots/list"), - params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() - }); - /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ - const CreateMessageResultSchema$1 = schemas_object({ - ...SamplingMessageSchema$1.shape, - model: schemas_string(), - stopReason: schemas_string().optional() - }); - /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ - const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); - /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ - const ElicitResultSchema$1 = schemas_object({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional() - }); - /** - * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed - * `elicitationId` (and the `notifications/elicitation/complete` channel it - * keyed) — the shared schema keeps the field because it is required on the - * frozen 2025-11-25 revision. - */ - const ElicitRequestURLParamsSchema$1 = schemas_object({ - mode: literal("url"), - message: schemas_string(), - url: schemas_string().url() - }); - /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ - const ElicitRequestSchema$1 = schemas_object({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** A single embedded input request (one of the three demoted server→client requests). */ - const InputRequestSchema = schemas_union([ - CreateMessageRequestSchema$1, - ListRootsRequestSchema$1, - ElicitRequestSchema$1 - ]); - /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ - const InputResponseSchema = schemas_union([ - CreateMessageResultSchema$1, - ListRootsResultSchema$1, - ElicitResultSchema$1 - ]); - /** Map of embedded input requests, keyed by server-assigned identifiers. */ - const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); - /** Map of embedded input responses, keyed by the corresponding request identifiers. */ - const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); - /** - * The wire InputRequiredResult: `resultType: 'input_required'` plus at least - * one of `inputRequests` / `requestState` (the at-least-one rule is enforced - * at the server seam, not by this parse shape). - */ - const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: schemas_string().optional() - }); - /** The retry-channel members carried by client-initiated requests on this revision. */ - const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: schemas_string().optional() - }; - /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ - const InputResponseRequestParamsSchema = schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape - }); - /** Post-lift request `_meta` (progressToken + extension keys; loose). */ - const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); - function wireRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...paramsShape - }) - }); - } - function dispatchRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: DispatchRequestMetaSchema.optional(), - ...paramsShape - }).optional() - }); - } - const callToolParamsShape = { - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional(), - ...retryParamsShape - }; - const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; - const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); - const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); - const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); - const GetPromptRequestSchema$1 = wireRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional(), - ...retryParamsShape - }); - const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); - const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); - const ReadResourceRequestSchema$1 = wireRequest("resources/read", { - uri: schemas_string(), - ...retryParamsShape - }); - const completeParamsShape = { - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }; - const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); - const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); - /** Anchor SubscriptionFilter (2026-only). */ - const SubscriptionFilterSchema$1 = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() - }); - const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; - const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); - /** - * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on - * the graceful-close result. Extends `ResultMetaObject` since spec PR - * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). - */ - const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); - /** - * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` - * response signalling that the subscription has ended gracefully (server - * shutdown). An abrupt transport close carries no response — the client treats - * stream-close-without-result as a disconnect. - */ - const SubscriptionsListenResultSchema$1 = looseObject({ - _meta: SubscriptionsListenResultMetaSchema$1, - resultType: ResultTypeSchema.default("complete") - }); - /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ - const dispatchRequestSchemas = { - "tools/call": dispatchRequest("tools/call", callToolParamsShape), - "tools/list": dispatchRequest("tools/list", paginatedParamsShape), - "prompts/get": dispatchRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }), - "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), - "resources/list": dispatchRequest("resources/list", paginatedParamsShape), - "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), - "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), - "completion/complete": dispatchRequest("completion/complete", completeParamsShape), - "server/discover": dispatchRequest("server/discover", {}), - "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) - }; - /** Dispatch (post-lift) result schemas, keyed by method — what the funnel - * validates AFTER `decodeResult` consumed `resultType`. */ - function liftedResult(shape) { - return looseObject({ - _meta: wireMeta, - ...shape - }); - } - const dispatchResultSchemas = { - "tools/call": liftedResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }), - "tools/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }), - "prompts/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/templates/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/read": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }), - "completion/complete": liftedResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }), - "server/discover": liftedResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }), - "subscriptions/listen": liftedResult({}) - }; - /** - * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the - * subscriptions/listen demux key typed when present. Only the anchor-exact - * SHAPE is modeled here — listen delivery itself (filter gating, demux, - * teardown) is #14 scope and not implemented by this module. - */ - const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); - /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ - const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ - method: literal("notifications/subscriptions/acknowledged"), - params: schemas_object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema$1 - }) - }); - /** - * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` - * is REQUIRED on this revision — the shared schema keeps it optional because - * the frozen 2025-11-25 shape declares it optional (task cancellation goes - * through `tasks/cancel` there). Requiredness is bare because no 2025-era - * traffic touches this module. - */ - const CancelledNotificationParamsSchema$1 = schemas_object({ - _meta: NotificationMetaSchema.optional(), - requestId: RequestIdSchema$1, - reason: schemas_string().optional() - }); - /** 2026-era `notifications/cancelled` (see the params fork above). */ - const CancelledNotificationSchema$1 = schemas_object({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - const notificationSchemas2026 = { - "notifications/cancelled": CancelledNotificationSchema$1, - "notifications/progress": ProgressNotificationSchema$1, - "notifications/message": LoggingMessageNotificationSchema$1, - "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, - "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, - "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, - "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, - "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 - }; - const wireResultResponse = (result) => schemas_object({ - jsonrpc: literal("2.0"), - id: schemas_union([schemas_string(), schemas_number().int()]), - result - }).strict(); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - RequestIdSchema: RequestIdSchema$1, - RoleSchema: RoleSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - RootSchema: RootSchema$1, - ClientCapabilities2026Schema, - ServerCapabilities2026Schema, - RequestMetaEnvelopeSchema, - ToolSchema: ToolSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - ResultTypeSchema, - ResultMetaSchema, - ResultSchema: ResultSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - CacheableResultSchema, - DiscoverResultSchema: DiscoverResultSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - InputRequestSchema, - InputResponseSchema, - InputRequestsSchema, - InputResponsesSchema, - InputRequiredResultSchema, - InputResponseRequestParamsSchema, - CallToolRequestSchema: CallToolRequestSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - DiscoverRequestSchema: DiscoverRequestSchema$1, - SubscriptionFilterSchema: SubscriptionFilterSchema$1, - SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, - SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, - SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, - dispatchRequestSchemas, - dispatchResultSchemas, - NotificationMetaSchema, - SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - notificationSchemas2026, - JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), - CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), - ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), - ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), - GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), - ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), - ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), - ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), - CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), - DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) - }; -} -let src_CX2iR2pK_memo; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2026() { - return src_CX2iR2pK_memo ??= build(); -} - -//#endregion -//#region ../core-internal/src/shared/resultCacheHints.ts -/** -* The operations whose results are cacheable on the 2026-07-28 revision (the -* `CacheableResult` extenders). This list is closed: no other operation's -* result ever receives cache fields from the SDK. -*/ -const CACHEABLE_RESULT_METHODS = [ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "resources/read", - "server/discover" -]; -/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ -function isCacheableResultMethod(method) { - return CACHEABLE_RESULT_METHODS.includes(method); -} -/** -* The symbol-keyed carrier for a configured cache hint on a result object. -* Symbol properties are invisible to JSON serialization, so the carrier can be -* attached era-blind: only the 2026-era encode seam consumes it. -*/ -const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); -/** -* Attaches a configured cache hint to a result as the encode-time fallback. -* Returns the result unchanged when there is nothing to attach. When a more -* specific hint is already attached, the two hints are combined per field -* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the -* per-registration hint attached by the feature layer keeps every field it -* sets, and the server-level per-operation hint only fills the fields the -* more specific hint leaves unset. -*/ -function attachCacheHintFallback(result, hint) { - if (hint === void 0) return result; - const attached = result[RESULT_CACHE_HINT_FALLBACK]; - if (attached === void 0) return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: hint - }; - const merged = {}; - const ttlMs = attached.ttlMs ?? hint.ttlMs; - if (ttlMs !== void 0) merged.ttlMs = ttlMs; - const cacheScope = attached.cacheScope ?? hint.cacheScope; - if (cacheScope !== void 0) merged.cacheScope = cacheScope; - return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: merged - }; -} -/** Reads the configured cache-hint fallback attached to a result, if any. */ -function cacheHintFallbackOf(result) { - return result[RESULT_CACHE_HINT_FALLBACK]; -} -/** -* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe -* integers are required because the wire schemas validate `ttlMs` as an -* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value -* outside that range is treated as invalid here so it falls through to the -* next author instead of being emitted and rejected downstream. -*/ -function isValidCacheTtlMs(value) { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; -} -/** Whether a value is a valid `cacheScope`. */ -function isValidCacheScope(value) { - return value === "public" || value === "private"; -} -/** -* Validates a configured cache hint at configuration time. Throws a -* `RangeError` naming the offending field, so misconfiguration fails at -* startup/registration rather than silently degrading at encode time. -*/ -function assertValidCacheHint(hint, context) { - if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); - if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); -} - -//#endregion -//#region ../core-internal/src/types/enums.ts -/** -* Error codes for protocol errors that cross the wire as JSON-RPC error responses. -* These follow the JSON-RPC specification and MCP-specific extensions. -*/ -let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { - ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; - ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; - /** - * Resource not found. - * - * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` - * misses answer `-32602` (Invalid Params) on every protocol revision per - * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to - * `-32602` at the era encode seam. The member stays importable so clients - * can recognise `-32002` from peers built on earlier SDK releases (the - * spec's "clients SHOULD also accept `-32002`" backwards-compatibility - * clause). Throw `ResourceNotFoundError` instead. - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; - /** - * Processing the request requires a capability the client did not declare - * in the request's `clientCapabilities` (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; - /** - * The request's protocol version is unknown to the server or unsupported - * by it (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; - return ProtocolErrorCode$1; -}({}); - -//#endregion -//#region ../core-internal/src/types/errors.ts -/** -* Protocol errors are JSON-RPC errors that cross the wire as error responses. -* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. -* -* `instanceof` on this class (and its subclasses) is brand-matched, so it works -* across separately bundled copies of the SDK — e.g. an error constructed by -* `@modelcontextprotocol/client` matches the class re-exported by -* `@modelcontextprotocol/server` in the same process. -*/ -var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "ProtocolError"; - stampErrorBrands(this, new.target); - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { - const errorData = data; - if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: errorData.supported, - requested: errorData.requested - }, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { - const errorData = data; - if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { - const errorData = data; - if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); - } - return new ProtocolError(code, message, data); - } -}; -/** -* Error type for a `resources/read` miss: the requested resource does not -* exist. The wire code is `-32602` (Invalid Params) on every protocol -* revision — the spec MUST for revision 2026-07-28, and the value the v1.x -* SDK has always emitted on earlier revisions. The error data echoes the -* requested URI. -* -* Recognise this error by checking `error.data` is exactly `{ uri: string }` -* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; -* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also -* accept `-32002` as resource not found — earlier SDK builds emitted that -* code, and {@linkcode ProtocolError.fromError} reconstructs this class for -* either code **when `error.data` carries `uri`** (a bare `-32002` without -* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks -* are brand-matched and work across separately bundled copies of the SDK. -*/ -var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); - } - constructor(uri, message = `Resource not found: ${uri}`) { - super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); - } - /** The URI that was requested and not found. */ - get uri() { - return this.data.uri; - } -}; -/** -* Specialized error type when a tool requires a URL mode elicitation. -* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. -*/ -var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); - } - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -}; -/** -* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol -* revision 2026-07-28): the request's protocol version is unknown to the server or -* unsupported by it. -* -* The error data lists the protocol versions the receiver supports (`supported`), -* so the sender can choose a mutually supported version and retry, and echoes the -* version that was requested (`requested`). -*/ -var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); - } - constructor(data, message = `Unsupported protocol version: ${data.requested}`) { - super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); - } - /** - * Protocol versions the receiver supports. - */ - get supported() { - return this.data.supported; - } - /** - * The protocol version that was requested. - */ - get requested() { - return this.data.requested; - } -}; -/** -* Error type for the `-32021` MissingRequiredClientCapability protocol error -* (protocol revision 2026-07-28): processing the request requires a capability -* the client did not declare in the request's `clientCapabilities`. -* -* The error data lists the missing capabilities (`requiredCapabilities`) in -* the `ClientCapabilities` shape, so the client can see exactly what it would -* have to declare for the request to be served. On HTTP, the response status -* is `400 Bad Request`. -* -* Recognize this error by its code and `data.requiredCapabilities`, or by -* `instanceof` — checks are brand-matched and work across separately bundled -* copies of the SDK. -*/ -var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); - } - constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { - super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); - } - /** - * The capabilities the server requires from the client to process the - * request (only the missing capabilities are listed). - */ - get requiredCapabilities() { - return this.data.requiredCapabilities; - } -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts -/** The default cache policy when neither the handler nor configuration provides one. */ -const DEFAULT_CACHE_TTL_MS = 0; -const DEFAULT_CACHE_SCOPE = "private"; -/** -* Request methods whose spec result vocabulary goes beyond `'complete'` on the -* 2026-07-28 revision: their results may be `input_required` (multi -* round-trip requests), so a handler-provided `resultType` passes through the -* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits -* a JSON-RPC result — termination is stream close (HTTP) or -* `notifications/cancelled` (stdio) per the spec. -*/ -const EXTENDED_RESULT_TYPE_METHODS = [ - "tools/call", - "prompts/get", - "resources/read" -]; -/** -* Step 1 of the encode contract: ensure the outbound result carries the -* required `resultType` discriminator. -* -* - No handler-provided value → stamp `'complete'`. -* - Handler-provided `'complete'` → kept as-is. -* - Handler-provided non-`'complete'` value on a method whose vocabulary -* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. -* The value is forwarded verbatim — the wire vocabulary is an open union and -* the SDK does not validate the string, so emitting a `resultType` the -* negotiated revision does not define is the handler author's -* responsibility. -* - Handler-provided non-`'complete'` value on any other method → internal -* error (loud): the value would be mis-typed on the wire, and silently -* rewriting it would hide a server bug. -*/ -function stampResultType(method, result) { - const provided = result["resultType"]; - if (provided === void 0) return { - ...result, - resultType: "complete" - }; - if (provided === "complete") return result; - if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); -} -/** -* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields -* on cacheable results. -* -* Applies only when the (post-stamp) `resultType` is `'complete'` and the -* method is one of the cacheable operations; everything else is returned -* untouched apart from removing the configured-hint carrier. Field resolution -* is per field, most specific author first: a valid handler-returned value, -* then the configured cache hint attached by the server layer, then the -* defaults. Handler-returned values are validated at encode time (`ttlMs` -* must be a non-negative integer, `cacheScope` must be `'public'` or -* `'private'`); invalid values are ignored rather than emitted. -*/ -function fillCacheFields(method, result) { - const fallback = cacheHintFallbackOf(result); - if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); - const provided = result; - const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); - const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); - const filled = { - ...provided, - ttlMs, - cacheScope - }; - delete filled[RESULT_CACHE_HINT_FALLBACK]; - return filled; -} -function isPlainObject$5(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Step 3 of the encode contract: stamp the server's identity into the -* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: -* servers SHOULD include it on every response). -* -* - No `serverInfo` supplied (a client instance, or a hand-constructed -* protocol object) → identity function. -* - The result's `_meta` already carries the key → kept as-is (the handler -* is the more specific author; mirrors the cache-fill resolution order). -* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: -* the stamp never rewrites handler material, and the malformed value fails -* loudly at the peer instead of being silently replaced here. -* - Otherwise → the key is added, preserving any other `_meta` entries. -* -* Runs for every result regardless of `resultType`: the anchor types -* `Result._meta` as `ResultMetaObject` on all results, `input_required` -* included. -*/ -function stampServerInfoMeta(result, serverInfo) { - if (serverInfo === void 0) return result; - const meta = result["_meta"]; - if (meta === void 0) return { - ...result, - _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } - }; - if (!isPlainObject$5(meta)) return result; - if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; - return { - ...result, - _meta: { - ...meta, - [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo - } - }; -} -function resolveTtlMs(fallback) { - return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; -} -function resolveCacheScope(fallback) { - return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; -} -function stripCacheHintFallback(result) { - const copy = { ...result }; - delete copy[RESULT_CACHE_HINT_FALLBACK]; - return copy; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts -/** -* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 -* multi round-trip requests), dispatch view. -* -* The three former server→client wire requests (`elicitation/create`, -* `sampling/createMessage`, `roots/list`) are NOT wire request methods on -* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an -* `input_required` result. The multi-round-trip driver dispatches those -* embedded payloads to the client's registered handlers through the normal -* handler machinery, and these are the schemas that dispatch parses them -* with: lenient where the anchor's wire-true artifacts are strict (an -* embedded request never carries the per-request `_meta` envelope), exact -* where the vocabulary forks (the sampling shapes compose the forked -* SamplingMessage/Tool payloads). -* -* Registry membership is intentionally NOT granted here — these methods stay -* absent from the 2026-era request registry (a peer sending one as a wire -* request still gets −32601 by absence). Only the codec's -* `inputRequestSchema`/`inputResponseSchema` accessors expose them. -*/ -/** The embedded input-request methods of the 2026-07-28 revision. */ -const INPUT_REQUEST_METHODS_2026 = [ - "elicitation/create", - "sampling/createMessage", - "roots/list" -]; -let maps; -function inputSchemaMaps() { - if (maps) return maps; - const s = buildSchemas2026(); - maps = { - request: { - "elicitation/create": schemas_object({ - method: literal("elicitation/create"), - params: s.ElicitRequestParamsSchema - }), - "sampling/createMessage": schemas_object({ - method: literal("sampling/createMessage"), - params: s.CreateMessageRequestParamsSchema - }), - "roots/list": schemas_object({ - method: literal("roots/list"), - params: looseObject({}).optional() - }) - }, - response: { - "elicitation/create": s.ElicitResultSchema, - "sampling/createMessage": s.CreateMessageResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps; -} -/** -* Forces the lazy embedded-request maps (and, through them, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmInputSchemaMaps2026() { - inputSchemaMaps(); -} -function isInputRequestMethod2026(method) { - return INPUT_REQUEST_METHODS_2026.includes(method); -} -function getInputRequestSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; -} -function getInputResponseSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/registry.ts -const requestMethodKeys = { - "tools/call": null, - "tools/list": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "completion/complete": null, - "server/discover": null, - "subscriptions/listen": null -}; -const notificationMethodKeys = { - "notifications/cancelled": null, - "notifications/progress": null, - "notifications/message": null, - "notifications/resources/updated": null, - "notifications/resources/list_changed": null, - "notifications/tools/list_changed": null, - "notifications/prompts/list_changed": null, - "notifications/subscriptions/acknowledged": null -}; -/** The 2026-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -/** The 2026-era notification-method set. */ -function hasNotificationMethod2026(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); -} -/** Result-map membership (same key set as the request map on this era). */ -function hasResultMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -function getRequestSchema2026(method) { - return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; -} -function getResultSchema2026(method) { - return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; -} -function getNotificationSchema2026(method) { - return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2026RequestMethods = Object.keys(requestMethodKeys); -const rev2026NotificationMethods = Object.keys(notificationMethodKeys); - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/codec.ts -function isPlainObject$4(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA = { - ok: false, - reason: "not-in-era" -}; -/** -* The reserved `_meta` keys an envelope must carry on this era (in reporting -* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a -* request without it is accepted (a present-but-malformed value still fails -* the envelope schema parse below). -*/ -const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; -/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ -function enforceDeletedFields(method, result) { - let next = result; - let copied = false; - const copy = () => { - if (!copied) { - next = { ...next }; - copied = true; - } - return next; - }; - const tools = result.tools; - if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { - if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; - const rest = { ...tool }; - delete rest["execution"]; - return rest; - }); - const capabilities = result.capabilities; - if (isPlainObject$4(capabilities) && "tasks" in capabilities) { - const rest = { ...capabilities }; - delete rest["tasks"]; - copy().capabilities = rest; - } - return next; -} -const rev2026Codec = { - era: "2026-07-28", - hasRequestMethod: hasRequestMethod2026, - hasNotificationMethod: hasNotificationMethod2026, - hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, - validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), - validateResult: (method, raw) => triState(getResultSchema2026(method), raw), - validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), - validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), - validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), - samplingResultVariant: () => NOT_IN_ERA, - outboundEnvelope(material) { - return { - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, - ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } - }; - }, - validateEnvelopeMeta(meta) { - const issues = []; - for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ - key, - problem: "missing" - }); - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); - if (!parsed.success) for (const issue of parsed.error.issues) { - const path = issue.path.map(String); - const key = path.length > 0 ? path.join(".") : "_meta"; - if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; - issues.push({ - key, - problem: issue.message - }); - } - return issues; - }, - projectCallToolResult: (result) => appendTextFallbackForNonObject(result), - inputRequestSchema: getInputRequestSchema2026, - decodeResult(method, raw) { - if (!isPlainObject$4(raw)) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) - }; - const rawResultType = raw["resultType"]; - if (rawResultType === void 0) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { - method, - violation: "missing-resultType" - }) - }; - if (typeof rawResultType !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { - method, - resultType: rawResultType - }) - }; - if (rawResultType === "input_required") { - const rawInputRequests = raw["inputRequests"]; - const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; - const requestState = raw["requestState"]; - if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { - method, - violation: "input-required-missing-both" - }) - }; - return { - kind: "input_required", - inputRequests, - ...typeof requestState === "string" && { requestState } - }; - } - if (rawResultType !== "complete") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { - resultType: rawResultType, - method - }) - }; - const wireResultSchemas = getWireResultSchemas(); - const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; - if (wireSchema !== void 0) { - const parsed = wireSchema.safeParse(raw); - if (!parsed.success) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) - }; - } - const lifted = { ...raw }; - delete lifted["resultType"]; - return { - kind: "complete", - result: lifted - }; - }, - encodeResult(method, result, serverInfo) { - return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope(material) { - if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); - if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; - } -}; -/** Wire-true result wrappers consulted by decode step 2, keyed by method — -* built once through the era's schema memo on the first decode. */ -let wireResultSchemasMemo; -function getWireResultSchemas() { - if (wireResultSchemasMemo) return wireResultSchemasMemo; - const s = buildSchemas2026(); - wireResultSchemasMemo = { - "tools/call": s.CallToolResultSchema, - "tools/list": s.ListToolsResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "completion/complete": s.CompleteResultSchema, - "server/discover": s.DiscoverResultSchema - }; - return wireResultSchemasMemo; -} -/** -* Forces the lazy wire-result wrapper map (and, through it, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. -*/ -function warmWireResultSchemas2026() { - getWireResultSchemas(); -} - -//#endregion -//#region ../core-internal/src/wire/codec.ts -/** -* The modern wire revision literal. Internal only — deliberately NOT a public -* constant (G-D2-4: no public modern-version constant ships before era-aware -* list semantics exist). -*/ -const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; -/** -* Era resolution, many-to-one (Q1-SD1): every modern-era revision -* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five -* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era -* codec (the DV-13 default posture — hand-constructed instances and -* unclassified traffic are legacy-era). This is the same era predicate the -* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern -* revision other than the literal '2026-07-28' must still resolve modern. -*/ -function src_CX2iR2pK_codecForVersion(version) { - return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; -} -/** -* The wire era an edge classification names (Q2 — produced at the -* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no -* longer resolves a codec FROM the classification: era is instance state, and -* a classified inbound message is VALIDATED against the instance era — a -* mismatch is an entry/routing error, never a per-message era switch. The -* exact `revision` wins over the coarse era flag when both are present. -*/ -function classifiedWireEra(classification) { - if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; - return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; -} -/** -* The derived spec-method universe: the union of every codec registry. A -* method in this set is era-gated at dispatch and send time; a method outside -* it is a consumer-owned extension method (era-blind, schema-explicit). -* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS -* table class is exactly what registry membership replaces). -*/ -function isSpecRequestMethod(method) { - return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); -} -function isSpecNotificationMethod(method) { - return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); -} -const ALL_CODECS = [rev2025Codec, rev2026Codec]; - -//#endregion -//#region ../core-internal/src/shared/envelope.ts -/** -* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). -* -* Pure, value-returning helpers used by the inbound HTTP classifier -* (`classifyInboundRequest`): claim detection and envelope validation with -* self-identifying issues. The envelope schema itself stays the wire layer's -* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps -* its outcomes into the shapes the validation ladder emits. -* -* Claim detection is deliberately narrow: a message claims the 2026-07-28 -* envelope mechanism if and only if the reserved protocol-version `_meta` key -* is present in `params._meta`. Other reserved keys (client info, client -* capabilities, log level), a bare `progressToken`, or unrelated keys under -* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their -* own — but once the claim key is present, a malformed envelope is a -* validation error, never a silent fall back to legacy handling. -* -* The wire-exact envelope schema, the required-key set, and the per-key issue -* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). -* This module never reaches into a per-revision wire module directly. -*/ -function isPlainObject$3(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** The `_meta` object of a message's params, when present. */ -function src_CX2iR2pK_requestMetaOf(params) { - if (!isPlainObject$3(params)) return void 0; - const meta = params["_meta"]; - return isPlainObject$3(meta) ? meta : void 0; -} -/** -* Whether a message's params carry the per-request envelope claim: the -* reserved protocol-version `_meta` key is present (regardless of whether the -* rest of the envelope is valid — validation is a separate, later step). -*/ -function src_CX2iR2pK_hasEnvelopeClaim(params) { - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; -} -/** -* The protocol version named by a message's envelope claim, when the claim is -* present and carries a string value. A present claim with a non-string value -* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a -* validation issue instead of a version. -*/ -function src_CX2iR2pK_envelopeClaimVersion(params) { - const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; - return typeof value === "string" ? value : void 0; -} -/** -* Validates a request's `_meta` object as a 2026-07-28 per-request envelope -* and reports problems as self-identifying issues (which key, what problem). -* -* Returns an empty array when the envelope is valid. Missing required keys are -* reported first (as `problem: 'missing'`), then schema violations inside -* present keys, in a stable order. -*/ -function src_CX2iR2pK_validateEnvelopeMeta(meta) { - return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); -} - -//#endregion -//#region ../core-internal/src/types/schemas.ts -var schemas_exports = /* @__PURE__ */ __exportAll({ - AnnotationsSchema: () => AnnotationsSchema, - AudioContentSchema: () => AudioContentSchema, - BaseMetadataSchema: () => BaseMetadataSchema, - BaseRequestParamsSchema: () => BaseRequestParamsSchema, - BlobResourceContentsSchema: () => BlobResourceContentsSchema, - BooleanSchemaSchema: () => BooleanSchemaSchema, - CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, - CallToolRequestSchema: () => CallToolRequestSchema, - CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, - CancelTaskRequestSchema: () => CancelTaskRequestSchema, - CancelTaskResultSchema: () => CancelTaskResultSchema, - CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, - CancelledNotificationSchema: () => CancelledNotificationSchema, - ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, - ClientNotificationSchema: () => ClientNotificationSchema, - ClientRequestSchema: () => ClientRequestSchema, - ClientResultSchema: () => ClientResultSchema, - ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, - CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, - CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, - CompleteRequestSchema: () => CompleteRequestSchema, - CompleteResultSchema: () => CompleteResultSchema, - ContentBlockSchema: () => ContentBlockSchema, - CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, - CreateMessageRequestSchema: () => CreateMessageRequestSchema, - CreateMessageResultSchema: () => CreateMessageResultSchema, - CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, - CreateTaskResultSchema: () => CreateTaskResultSchema, - CursorSchema: () => CursorSchema, - DiscoverRequestSchema: () => DiscoverRequestSchema, - DiscoverResultSchema: () => DiscoverResultSchema, - ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, - ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, - ElicitRequestSchema: () => ElicitRequestSchema, - ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, - ElicitResultSchema: () => ElicitResultSchema, - ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, - ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, - EmbeddedResourceSchema: () => EmbeddedResourceSchema, - EmptyResultSchema: () => EmptyResultSchema, - EnumSchemaSchema: () => EnumSchemaSchema, - GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, - GetPromptRequestSchema: () => GetPromptRequestSchema, - GetPromptResultSchema: () => GetPromptResultSchema, - GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, - GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, - GetTaskRequestSchema: () => GetTaskRequestSchema, - GetTaskResultSchema: () => GetTaskResultSchema, - IconSchema: () => IconSchema, - IconsSchema: () => IconsSchema, - ImageContentSchema: () => ImageContentSchema, - ImplementationSchema: () => ImplementationSchema, - InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, - InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, - InitializeResultSchema: () => InitializeResultSchema, - InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, - JSONArraySchema: () => JSONArraySchema, - JSONObjectSchema: () => JSONObjectSchema, - JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, - JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, - JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, - JSONRPCRequestSchema: () => JSONRPCRequestSchema, - JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, - JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, - JSONValueSchema: () => JSONValueSchema, - LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, - ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, - ListPromptsRequestSchema: () => ListPromptsRequestSchema, - ListPromptsResultSchema: () => ListPromptsResultSchema, - ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, - ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, - ListResourcesRequestSchema: () => ListResourcesRequestSchema, - ListResourcesResultSchema: () => ListResourcesResultSchema, - ListRootsRequestSchema: () => ListRootsRequestSchema, - ListRootsResultSchema: () => ListRootsResultSchema, - ListTasksRequestSchema: () => ListTasksRequestSchema, - ListTasksResultSchema: () => ListTasksResultSchema, - ListToolsRequestSchema: () => ListToolsRequestSchema, - ListToolsResultSchema: () => ListToolsResultSchema, - LoggingLevelSchema: () => LoggingLevelSchema, - LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, - LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, - ModelHintSchema: () => ModelHintSchema, - ModelPreferencesSchema: () => ModelPreferencesSchema, - MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, - NotificationSchema: () => NotificationSchema, - NotificationsParamsSchema: () => NotificationsParamsSchema, - NumberSchemaSchema: () => NumberSchemaSchema, - PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, - PaginatedRequestSchema: () => PaginatedRequestSchema, - PaginatedResultSchema: () => PaginatedResultSchema, - PingRequestSchema: () => PingRequestSchema, - PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, - ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, - ProgressNotificationSchema: () => ProgressNotificationSchema, - ProgressSchema: () => ProgressSchema, - ProgressTokenSchema: () => ProgressTokenSchema, - PromptArgumentSchema: () => PromptArgumentSchema, - PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, - PromptMessageSchema: () => PromptMessageSchema, - PromptReferenceSchema: () => PromptReferenceSchema, - PromptSchema: () => PromptSchema, - ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, - ReadResourceRequestSchema: () => ReadResourceRequestSchema, - ReadResourceResultSchema: () => ReadResourceResultSchema, - RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, - RequestIdSchema: () => RequestIdSchema, - RequestMetaSchema: () => RequestMetaSchema, - RequestSchema: () => RequestSchema, - ResourceContentsSchema: () => ResourceContentsSchema, - ResourceLinkSchema: () => ResourceLinkSchema, - ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, - ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, - ResourceSchema: () => ResourceSchema, - ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, - ResourceTemplateSchema: () => ResourceTemplateSchema, - ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, - ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, - ResultMetaObjectSchema: () => ResultMetaObjectSchema, - ResultSchema: () => ResultSchema, - RoleSchema: () => RoleSchema, - RootSchema: () => RootSchema, - RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, - SamplingContentSchema: () => SamplingContentSchema, - SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, - SamplingMessageSchema: () => SamplingMessageSchema, - ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, - ServerNotificationSchema: () => ServerNotificationSchema, - ServerRequestSchema: () => ServerRequestSchema, - ServerResultSchema: () => ServerResultSchema, - ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, - SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, - SetLevelRequestSchema: () => SetLevelRequestSchema, - SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, - StringSchemaSchema: () => StringSchemaSchema, - SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, - SubscribeRequestSchema: () => SubscribeRequestSchema, - SubscriptionFilterSchema: () => SubscriptionFilterSchema, - SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, - SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, - SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, - SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, - SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, - SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, - TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, - TaskCreationParamsSchema: () => TaskCreationParamsSchema, - TaskMetadataSchema: () => TaskMetadataSchema, - TaskSchema: () => TaskSchema, - TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, - TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, - TaskStatusSchema: () => TaskStatusSchema, - TextContentSchema: () => TextContentSchema, - TextResourceContentsSchema: () => TextResourceContentsSchema, - TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, - ToolAnnotationsSchema: () => ToolAnnotationsSchema, - ToolChoiceSchema: () => ToolChoiceSchema, - ToolExecutionSchema: () => ToolExecutionSchema, - ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, - ToolResultContentSchema: () => ToolResultContentSchema, - ToolSchema: () => ToolSchema, - ToolUseContentSchema: () => ToolUseContentSchema, - UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, - UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, - UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, - UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema -}); - -//#endregion -//#region ../core-internal/src/types/guards.ts -/** -* Validates and parses an unknown value as a JSON-RPC message. -* -* Use this to validate incoming messages in custom transport implementations. -* Throws if the value does not conform to the JSON-RPC message schema. -* -* @param value - The value to validate (typically a parsed JSON object). -* @returns The validated {@linkcode JSONRPCMessage}. -* @throws If validation fails. -*/ -function parseJSONRPCMessage(value) { - return JSONRPCMessageSchema.parse(value); -} -const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. -*/ -const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode CallToolResult}. -* -* This is a consumer-side VALUE check against the neutral model, not a wire -* validator: a raw wire object that additionally carries wire-only members -* (e.g. `resultType`) still passes through the loose index signature. Use a -* transport-level parse to validate raw wire traffic. -* -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. -*/ -const isCallToolResult = (value) => { - if (typeof value !== "object" || value === null || value.content === void 0) return false; - return CallToolResultSchema.safeParse(value).success; -}; -/** -* Checks whether a value is an input-required result (protocol revision -* 2026-07-28): the multi-round-trip return shape discriminated by -* `resultType: 'input_required'`. -* -* This is a discriminator check, not a full validator — the at-least-one rule -* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` -* builder and re-checked by the server seam for hand-built values. -* -* @param value - The value to check. -* @returns True if the value carries the `input_required` discriminator. -*/ -const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; -/** -* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. -* -* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK -* runtime; kept importable for interoperability only. -*/ -const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); -} - -//#endregion -//#region ../core-internal/src/shared/mcpParamHeaders.ts -/** The fixed prefix every custom-parameter header carries. */ -const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; -/** The schema-extension property name a tool's `inputSchema` carries. */ -const X_MCP_HEADER_KEY = "x-mcp-header"; -/** -* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control -* characters (including CR/LF), and the listed delimiters. -*/ -const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -/** -* JSON Schema `type` values the spec admits on an `x-mcp-header` property. -* -* The spec text names `integer`, `string`, `boolean` and explicitly excludes -* `number`. The published conformance referee at the pinned release ships its -* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` -* parameters and expects the client to mirror them, so `number` is accepted -* here so that the conformance gate passes; the discrepancy is tracked -* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. -*/ -const PERMITTED_X_MCP_HEADER_TYPES = new Set([ - "string", - "integer", - "boolean", - "number" -]); -/** -* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations -* and validate every constraint the spec places on them. Returns either the -* collected declarations (possibly empty) or the first violated constraint. -* -* The walk descends through `properties` at any depth (the spec's "any nesting -* depth" clause). The static-reachability MUST is enforced as a structural -* sweep: every position the chain MUST NOT pass through (`items`/ -* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, -* `$defs`, `$ref` targets within `$defs`) is visited too, and an -* `x-mcp-header` found anywhere on that path invalidates the schema — "an -* annotation anywhere else makes the tool definition invalid". -*/ -function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { - const declarations = []; - const seenLower = /* @__PURE__ */ new Map(); - const visit = (node, path, reachable) => { - if (node === null || typeof node !== "object") return void 0; - const schema = node; - if (X_MCP_HEADER_KEY in schema) { - if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; - const raw = schema[X_MCP_HEADER_KEY]; - if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; - if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; - const type = typeof schema.type === "string" ? schema.type : void 0; - if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; - const lower = raw.toLowerCase(); - const prior = seenLower.get(lower); - if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; - seenLower.set(lower, raw); - declarations.push({ - path, - headerName: raw, - type - }); - } - const properties = schema.properties; - if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { - const fault$1 = visit(child, [...path, key], reachable); - if (fault$1 !== void 0) return fault$1; - } - for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { - const sub = schema[k]; - if (sub === void 0) continue; - const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; - for (const branch of branches) { - const fault$1 = visit(branch, [...path, `<${k}>`], false); - if (fault$1 !== void 0) return fault$1; - } - } - }; - const fault = visit(inputSchema, [], true); - return fault === void 0 ? { - valid: true, - declarations - } : { - valid: false, - reason: fault - }; -} -/** -* JSON Schema keywords whose subschemas the SEP-2243 static-reachability -* constraint excludes from the `properties`-only chain. An `x-mcp-header` -* found under any of these invalidates the tool definition. -*/ -const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions" -]; -/** -* Subschema-carrying keywords whose value is a `name → subschema` object -* (not a single subschema or array of subschemas). The visit branches over -* `Object.values()` for these. -*/ -const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ - "patternProperties", - "dependentSchemas", - "$defs", - "definitions" -]); -function pathName(path) { - return path.length === 0 ? "" : path.join("."); -} -const BASE64_SENTINEL_PREFIX = "=?base64?"; -const BASE64_SENTINEL_SUFFIX = "?="; -const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; -const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; -/** -* Convert a primitive argument value to its string representation per the -* spec's type-conversion rules: strings pass through, integers and numbers -* become their decimal string, booleans become lowercase `'true'` / `'false'`. -* Non-finite numbers and integers outside the safe range are refused (the -* caller treats `undefined` as "do not emit a header for this value"). -*/ -function mcpParamPrimitiveToString(value) { - if (typeof value === "string") return value; - if (typeof value === "boolean") return value ? "true" : "false"; - if (typeof value === "number") { - if (!Number.isFinite(value)) return void 0; - if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; - return String(value); - } -} -function base64ToUtf8(b64) { - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return new TextDecoder("utf-8", { fatal: true }).decode(bytes); -} -/** -* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, -* the payload is decoded as UTF-8; otherwise the value is returned as-is. -* Returns `undefined` when the sentinel is present but the payload is not -* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject -* such values. -*/ -function decodeMcpParamValue(value) { - if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; - const b64 = value.slice(9, value.length - 2); - if (!BASE64_CANONICAL.test(b64)) return void 0; - try { - return base64ToUtf8(b64); - } catch { - return; - } -} -function valueAtPath(root, path) { - let node = root; - for (const key of path) { - if (node === null || typeof node !== "object") return void 0; - node = node[key]; - } - return node; -} -/** -* The header/body comparison the server performs at tool-resolution time. -* -* For each `x-mcp-header` declaration on the named tool: when the body -* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be -* present and decode to an equal value; when the body value is `null` or -* absent the server MUST NOT expect the header (a present header is ignored). -* A sentinel-carrying header whose payload is not canonical Base64 / valid -* UTF-8 is rejected as invalid characters. -* -* Integer-typed declarations are compared numerically (the spec's SHOULD — -* `42.0` and `42` are equal); everything else is compared as decoded strings. -* -* Returns `undefined` when every check passes, or an -* {@linkcode InboundLadderRejection} carrying the same `-32020` -* (`HeaderMismatch`) shape the inbound classifier emits for the -* standard-header cross-checks — `400 Bad Request` with the disagreeing pair -* in `data.mismatch`. -*/ -function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { - for (const decl of declarations) { - const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; - const headerValue = headers.get(headerKey); - const bodyRaw = valueAtPath(args, decl.path); - if (bodyRaw === void 0 || bodyRaw === null) continue; - const bodyString = mcpParamPrimitiveToString(bodyRaw); - if (bodyString === void 0) continue; - if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); - const decoded = decodeMcpParamValue(headerValue); - if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); - if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); - } -} -/** -* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` -* disagreement. Same shape as the inbound classifier's standard-header -* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing -* pair, `settled: true`); only the rung differs because this check runs at the -* pre-dispatch step against a known tool's schema rather than at the edge. -*/ -function paramHeaderMismatchRejection(cell, header, body) { - return { - kind: "reject", - rung: "param-header-validation", - cell, - httpStatus: 400, - code: HEADER_MISMATCH_ERROR_CODE, - message: `Bad Request: the request headers and body disagree: ${body}`, - data: { mismatch: { - header, - body - } }, - settled: true - }; -} - -//#endregion -//#region ../core-internal/src/shared/inboundClassification.ts -/** -* Inbound HTTP request classification and the inbound validation ladder -* (protocol revision 2026-07-28). -* -* `classifyInboundRequest` is the body-primary era predicate for an HTTP -* entry that serves both protocol eras on one endpoint. It is evaluated -* exactly once, at the entry boundary, on the already-parsed request body: -* -* - `initialize` is a legacy-era request by definition (the modern era has no -* `initialize` handshake) — unless it carries a valid envelope claim naming -* a modern revision, in which case the claim wins and the request is -* classified like any other enveloped request (the modern era then answers -* it with method-not-found, exactly like every other method it does not -* define). -* - A request whose `params._meta` carries the reserved protocol-version key -* claims the per-request envelope mechanism and classifies into the era the -* named revision belongs to (a malformed envelope behind a present claim is -* a validation error, never a silent fall back to legacy handling). -* - A request without a claim is legacy-era traffic. -* - The `MCP-Protocol-Version` header is a cross-check only: it never -* upgrades or downgrades a body-derived classification, and a disagreement -* between header and body is an explicit ladder outcome. -* - Notifications carry no envelope claim of their own under the current -* spec, so for notification POSTs without a body claim the modern header is -* determinative; the `Mcp-Method` header is validated against the body when -* the message classifies modern and is never enforced on legacy traffic. -* A notification that does carry a claim is treated body-primary like a -* request, and a malformed claim is rejected the same way a request's -* malformed claim is — never silently resolved against the header. -* The notification-POST header cross-checks here are an SDK-defensive -* posture, not a spec requirement: the spec leaves header rules for posted -* notifications undefined (core client notifications do not occur over -* Streamable HTTP); applying the request rules symmetrically is what an -* ecosystem custom-notification POST expects, and the −32020 cells stay -* passing for them. -* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era -* session operations: the modern era is `POST`-only, so they are routed to -* legacy serving when it is configured and rejected otherwise. -* - Array (batch) bodies are classified element-wise: an array containing a -* modern-claiming or invalid element is rejected, an all-legacy array is -* legacy traffic unchanged, and a single-element array is still an array. -* -* The classifier returns plain values (it never throws and never touches a -* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection -* carrying the JSON-RPC error to emit and the HTTP status to emit it with. -* Legacy routing outcomes deliberately carry NO `MessageClassification` — -* legacy and hand-wired traffic is never classified, which keeps its -* dispatch behavior byte-identical to today's. -* -* Error codes for the modern-path rejection cells follow the published -* conformance suite (and the spec text it asserts): -* -* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header -* disagreeing with the body, or the `Mcp-Method` header disagreeing with the -* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. -* - A request whose protocol-version header names a modern revision but whose -* body carries no `_meta` envelope claim — including an envelope present but -* missing the required protocol-version key — is rejected with `-32602` -* (invalid params) naming the missing key(s), on HTTP 400. -* -* Should a future spec revision or conformance release change these -* assignments, the affected cells are re-derived against that release; the -* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark -* a cell provisional again while such a change is in flight. -*/ -/** -* The error code emitted for header/body cross-check mismatches: the -* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or -* with the body's classification), and the `Mcp-Method` header disagreeing -* with the body method. -* -* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 -* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted -* by the published conformance suite for header-validation failures. It has no -* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era -* wire vocabulary; the validation ladder is its only emitter. -*/ -const HEADER_MISMATCH_ERROR_CODE = -32020; -/** -* The inbound validation ladder, expressed as data rather than control flow. -* -* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the -* dispatch rungs are evaluated by the protocol layer once the classified -* message is injected into a per-request server instance (the era registry -* gate, the envelope requiredness check, and per-method params validation). -* The client-capability rung is evaluated by the HTTP entry itself, -* pre-dispatch, on the validated envelope the classifier produced — see that -* rung's rationale for the ordering caveat. The order is the precedence: a -* request that fails several rungs is answered by the earliest one. -*/ -const INBOUND_VALIDATION_LADDER = [ - { - rung: "http-method", - order: 1, - evaluatedAt: "edge", - codes: [-32e3], - conformance: [], - rationale: "The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read." - }, - { - rung: "jsonrpc-shape", - order: 2, - evaluatedAt: "edge", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest], - conformance: ["server-stateless"], - rationale: "The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic." - }, - { - rung: "era-classification", - order: 3, - evaluatedAt: "edge", - codes: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion], - conformance: [ - "server-stateless", - "http-header-validation", - "http-custom-header-server-validation" - ], - rationale: "Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions." - }, - { - rung: "envelope", - order: 4, - evaluatedAt: "edge", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: ["server-stateless"], - rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." - }, - { - rung: "method-registry", - order: 5, - evaluatedAt: "dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], - conformance: ["server-stateless"], - rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." - }, - { - rung: "request-params", - order: 6, - evaluatedAt: "dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: [], - rationale: "Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table." - }, - { - rung: "standard-header-validation", - order: 7, - evaluatedAt: "pre-dispatch", - codes: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-header-validation"], - rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted." - }, - { - rung: "client-capabilities", - order: 8, - evaluatedAt: "pre-dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], - conformance: ["server-stateless"], - rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." - }, - { - rung: "param-header-validation", - order: 9, - evaluatedAt: "pre-dispatch", - codes: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-custom-header-server-validation"], - rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." - } -]; -/** -* HTTP status for ladder-originated JSON-RPC error codes. -* -* Keyed on origin, not on the bare code: this table only applies to errors -* the ladder (or a pre-handler protocol gate) produced. Errors produced by -* request handlers — whatever their code — stay in-band on HTTP 200, and are -* never mapped to an HTTP status by this table; in particular `-32603` and -* domain-specific codes never become a blanket 500. The single exception is -* `MissingRequiredClientCapability` (-32021) — see -* {@linkcode httpStatusForErrorCode}. -* -* `-32602` (invalid params) deliberately has NO entry: the only invalid-params -* rejection that maps to HTTP 400 is the classifier's own envelope rung -* short-circuit, which carries its HTTP status directly. A dispatch- or -* handler-produced invalid-params error is always in-band. -*/ -const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { - [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, - [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, - [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, - [HEADER_MISMATCH_ERROR_CODE]: 400 -}; -/** -* The HTTP status to answer a JSON-RPC error with, keyed on the error's -* origin. `in-band` errors (anything produced by a request handler) are -* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP -* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), -* whose 400 the spec mandates on the error itself with no origin condition, -* and which the SDK genuinely produces after dispatch (the `input_required` -* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` -* is NOT that peer's spec error and stays in-band like every other handler -* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. -* -* The per-request transport intentionally does NOT delegate to this function: -* its `?? 400` ladder fallback is only correct for entry-gate codes known to -* the table, and would wrongly map dispatch-window errors outside it (a -* window `-32602` must stay in-band on 200). The transport indexes the table -* directly; keep the two in agreement when editing either. -*/ -function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { - if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; - return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; -} -function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { - return { - kind: "reject", - rung, - cell, - httpStatus, - code: error.code, - message: error.message, - ...error.data !== void 0 && { data: error.data }, - settled - }; -} -function crossCheckMismatch(cell, header, body, rung = "era-classification") { - return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { - header, - body - } }), true); -} -/** -* The methods whose body carries a `params.name` / `params.uri` value the -* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 -* § Standard Request Headers, `Required For` column). -*/ -const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ - "tools/call": "name", - "prompts/get": "name", - "resources/read": "uri" -})); -/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ -function stripHttpOws(value) { - let start = 0; - while (start < value.length) { - const code = value.codePointAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - let end = value.length; - while (end > start) { - const code = value.codePointAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === value.length ? value : value.slice(start, end); -} -/** -* SEP-2243 standard-header server-side validation, evaluated by the HTTP -* entry on a modern-classified request immediately after -* {@linkcode classifyInboundRequest} returns a modern route. -* -* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, -* `standard-header-validation` rung — the same shape -* {@linkcode classifyInboundRequest} already emits on the edge -* `era-classification` rung for the `MCP-Protocol-Version` and -* `Mcp-Method` *mismatch* cells) when: -* -* - the required `Mcp-Method` header is absent; -* - the required `Mcp-Name` header is absent on a `tools/call`, -* `prompts/get`, or `resources/read` request whose body carries the -* `params.name` / `params.uri` value the header mirrors; -* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or -* - the (decoded) `Mcp-Name` value disagrees with the body's -* `params.name` / `params.uri`. -* -* Returns `undefined` (pass) for notifications (the spec table reads -* "All requests"), for methods that have no `Mcp-Name` source, and when the -* headers agree with the body. Never enforced on legacy traffic — the entry -* only calls this on a modern route. -* -* Kept separate from {@linkcode classifyInboundRequest} so that a body-only -* call to the classifier (no headers passed) keeps routing a modern request -* unchanged: the classifier remains a pure body-primary router, and this -* function is the presence/`Mcp-Name` half of the standard-header rung the -* entry layers on top. -*/ -function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { - if (route.messageKind !== "request") return; - const method = route.message.method; - if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); - const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; - if (sourceField === void 0) return; - const sourceValue = route.message.params?.[sourceField]; - const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; - if (request.mcpNameHeader === void 0) { - if (bodyValue === void 0) return; - return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); - } - const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); - const decoded = decodeMcpParamValue(normalizedNameHeader); - if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); - if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); -} -function isPlainObject$2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function classificationForClaim(claimedVersion) { - if (claimedVersion === void 0) return { era: "modern" }; - return { - era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", - revision: claimedVersion - }; -} -/** -* Whether a request's params carry a per-request envelope claim that is both -* well-formed and names a modern protocol revision. -* -* Used by the `initialize` precedence rule: only such a claim overrides the -* `initialize` ⇒ legacy-handshake classification — a request carrying a valid -* modern envelope is a modern request regardless of its method name, and the -* modern era then answers `initialize` exactly like any other method it does -* not define (method-not-found). A malformed claim, or one naming a pre-2026 -* revision, keeps the legacy-handshake routing unchanged. -* -* Exported on the core internal barrel for the stdio serving entry, which -* applies the same precedence rule to a connection's opening message; not -* public API. -*/ -function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { - if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; -} -function classifyBatch(body) { - if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); - for (const element of body) { - if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); - if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); - } - return { - kind: "legacy", - reason: "batch" - }; -} -function classifyRequestBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { - if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); - const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "request", - message: body, - classification: classificationForClaim(claimedVersion) - }; - } - if (headerNamesModern) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); - const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; - return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); - } - return { - kind: "legacy", - reason: "no-claim", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -function classifyNotificationBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { - key: PROTOCOL_VERSION_META_KEY, - problem: "expected a protocol version string" - }; - return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); - } - if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - const classification = classificationForClaim(claimedVersion); - if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification - }; - } - if (headerNamesModern) { - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification: { - era: "modern", - revision: headerVersion - } - }; - } - return { - kind: "legacy", - reason: "notification", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -/** -* Classifies one inbound HTTP request for dual-era serving. -* -* The body-primary predicate, evaluated once at the entry boundary: see the -* module documentation for the rules. Returns a routing outcome (`legacy` or -* `modern`) or a ladder rejection; it never throws. -*/ -function src_CX2iR2pK_classifyInboundRequest(request) { - request = { - ...request, - ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, - ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, - ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } - }; - if (request.httpMethod.toUpperCase() !== "POST") return { - kind: "legacy", - reason: "http-method" - }; - const body = request.body; - if (Array.isArray(body)) return classifyBatch(body); - if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { - kind: "legacy", - reason: "response" - }; - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); - return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); -} -/** -* The rejection a modern-only endpoint (no legacy serving configured) -* answers a legacy-classified request with. -* -* - Envelope-less requests (including `initialize`) are answered with the -* unsupported-protocol-version error carrying the endpoint's supported -* versions and echoing the version the request named (when it named one — -* `requested` is omitted rather than fabricated when the request named no -* version at all), so a legacy client can discover what the endpoint serves -* from the error alone. -* - Posted responses and batch arrays are invalid requests on the modern era. -* - Non-`POST` methods are not allowed. -* - Legacy-classified notifications return `undefined`: the caller answers -* 202 with no body and does not dispatch the notification (accept-and-drop). -*/ -function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { - switch (route.reason) { - case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); - case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); - case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); - case "notification": return; - case "initialize": - case "no-claim": { - const requested = route.requestedVersion; - return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: [...supportedVersions], - requested - }), true); - } - } -} - -//#endregion -//#region ../core-internal/src/util/schema.ts -/** -* Internal Zod schema utilities for protocol handling. -* These are used internally by the SDK for protocol message validation. -*/ -/** -* Parses data against a Zod schema (synchronous). -* Returns a discriminated union with success/error. -*/ -function parseSchema(schema, data) { - return parse_safeParse(schema, data); -} -/** -* Union of the declared shape keys across several Zod object schemas. -*/ -function shapeKeys(schemas) { - return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); -} - -//#endregion -//#region ../core-internal/src/util/standardSchema.ts -/** -* Standard Schema utilities for user-provided schemas. -* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. -* @see https://standardschema.dev -*/ -function isStandardSchema(schema) { - if (schema == null) return false; - const schemaType = typeof schema; - if (schemaType !== "object" && schemaType !== "function") return false; - if (!("~standard" in schema)) return false; - return typeof schema["~standard"]?.validate === "function"; -} -let warnedZodFallback = false; -/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ -const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; -/** -* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. -* -* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt -* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). -* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, -* so for `io: 'input'` this function defaults `type` to `"object"` when absent -* and throws on an explicit non-object `type` (e.g. `z.string()`). For -* `io: 'output'` a non-object root is returned as-is; the `"object"` default is -* applied only when the root is provably object-shaped. -*/ -function standardSchemaToJsonSchema(schema, io = "input") { - const std = schema["~standard"]; - let result; - if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); - else if (std.vendor === "zod") { - if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema()."); - if (!warnedZodFallback) { - warnedZodFallback = true; - console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning."); - } - result = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io - }); - } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); - if (io === "output") { - if (result.type !== void 0) return result; - return isProvablyObjectShapedRoot(result) ? { - type: "object", - ...result - } : result; - } - if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); - return { - type: "object", - ...result - }; -} -/** -* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords -* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a -* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively -* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to -* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. -*/ -function isProvablyObjectShapedRoot(schema) { - if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; - for (const key of [ - "oneOf", - "anyOf", - "allOf" - ]) { - const members = schema[key]; - if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); - } - return false; -} -function formatIssue(issue) { - if (!issue.path?.length) return issue.message; - return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; -} -async function validateStandardSchema(schema, data) { - const result = await schema["~standard"].validate(data); - if (result.issues && result.issues.length > 0) return { - success: false, - error: result.issues.map((i) => formatIssue(i)).join(", ") - }; - return { - success: true, - data: result.value - }; -} -function zodEmittedPattern(schema) { - const jsonSchema = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io: "input" - }); - return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; -} -const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; -function datetimeReferenceSchemas(pattern) { - const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); - const precisions = [ - void 0, - -1, - 0 - ]; - if (fractionDigits) precisions.push(Number(fractionDigits[1])); - return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ - local, - offset, - precision - })))); -} -function referencePatternsForFormat(format, pattern) { - let referenceSchemas; - switch (format) { - case "email": - referenceSchemas = [schemas_email()]; - break; - case "uri": - referenceSchemas = [schemas_url()]; - break; - case "date": - referenceSchemas = [iso_date()]; - break; - case "date-time": - referenceSchemas = datetimeReferenceSchemas(pattern); - break; - } - return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); -} -/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ -function isLibraryFormatPattern(format, pattern, vendor) { - if (vendor !== "zod") return true; - return referencePatternsForFormat(format, pattern).has(pattern); -} -function promptArgumentsFromStandardSchema(schema) { - const jsonSchema = standardSchemaToJsonSchema(schema, "input"); - const properties = jsonSchema.properties || {}; - const required = jsonSchema.required || []; - return Object.entries(properties).map(([name, prop]) => ({ - name, - description: prop?.description, - required: required.includes(name) - })); -} - -//#endregion -//#region ../core-internal/src/shared/elicitation.ts -function isJsonObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function convertStandardElicitationSchema(schema) { - try { - return standardSchemaToJsonSchema(schema, "input"); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); - } -} -const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ - "$comment", - "deprecated", - "description", - "examples", - "readOnly", - "title", - "writeOnly" -]); -function isAnnotationOnlyJsonSchemaKeyword(key) { - return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); -} -const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); -const PROPERTY_KEYS_BY_TYPE = { - string: shapeKeys([ - StringSchemaSchema, - UntitledSingleSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema, - LegacyTitledEnumSchemaSchema - ]), - number: shapeKeys([NumberSchemaSchema]), - integer: shapeKeys([NumberSchemaSchema]), - boolean: shapeKeys([BooleanSchemaSchema]), - array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) -}; -const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); -/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ -function walkProperty(node, path, vendor, unsupported) { - if (!isJsonObject(node)) return node; - const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; - if (allowedKeys === void 0) return node; - const pruned = {}; - for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; - else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { - if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; - else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); - } else unsupported.push(`${path}.${key}`); - return pruned; -} -/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ -function walkRequestedSchema(converted, vendor) { - const pruned = {}; - const unsupported = []; - for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); - else if (ROOT_KEYS.has(key)) pruned[key] = value; - else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); - if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); - return pruned; -} -/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ -function describeUnsupportedProperties(pruned, fallback) { - if (!isJsonObject(pruned.properties)) return fallback; - const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); - return offenders.length > 0 ? offenders.join(", ") : fallback; -} -function findDroppedConstraintPaths(original, parsed, path = "") { - if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); - if (!isJsonObject(original) || !isJsonObject(parsed)) return []; - return Object.entries(original).flatMap(([key, value]) => { - const childPath = path ? `${path}.${key}` : key; - if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; - return findDroppedConstraintPaths(value, parsed[key], childPath); - }); -} -/** Converts an authoring-friendly elicitation input into its wire-ready form. */ -function normalizeElicitInputParams(input) { - if (!isStandardSchema(input.requestedSchema)) return { - ...input, - mode: "form", - requestedSchema: input.requestedSchema - }; - const vendor = input.requestedSchema["~standard"].vendor; - const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); - const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); - const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); - if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); - const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); - if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); - return { - ...input, - mode: "form", - requestedSchema: parsed.data - }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequired.ts -/** -* Authoring helpers for multi-round-trip requests (protocol revision -* 2026-07-28). -* -* A handler for one of the multi-round-trip methods (`tools/call`, -* `prompts/get`, `resources/read`) requests additional client input by -* returning an {@linkcode InputRequiredResult} instead of a final result. The -* helpers here build that return value and its embedded requests as NEUTRAL -* values; only the 2026-07-28 wire codec maps them to/from the wire. The -* 2025-era codec has no input-required vocabulary — on a 2025-era request the -* server's legacy shim (on by default) fulfils the embedded requests as real -* server→client requests and re-enters the handler, so the same return shape -* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores -* the pre-shim loud failure. -* -* There is no nominal brand: `resultType: 'input_required'` is the -* discriminator, and hand-built result literals are equally legal — the -* server seam re-checks the at-least-one rule for them. -*/ -function buildInputRequired(spec) { - const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; - const hasRequestState = typeof spec.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)"); - return { - resultType: "input_required", - ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, - ...spec.requestState !== void 0 && { requestState: spec.requestState } - }; -} -/** -* Builder for the input-required return value of multi-round-trip handlers, -* with per-kind constructors for the embedded requests -* (`inputRequired.elicit`, `inputRequired.elicitUrl`, -* `inputRequired.createMessage`, `inputRequired.listRoots`). -* -* @example Write-once tool requesting confirmation -* ```ts -* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { -* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); -* if (!confirmed) { -* return inputRequired({ -* inputRequests: { -* confirm: inputRequired.elicit({ -* message: `Deploy to ${env}?`, -* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } -* }) -* } -* }); -* } -* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; -* }); -* ``` -*/ -const inputRequired = Object.assign(buildInputRequired, { - elicit(params) { - try { - return { - method: "elicitation/create", - params: normalizeElicitInputParams(params) - }; - } catch (error) { - throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; - } - }, - elicitUrl(params) { - return { - method: "elicitation/create", - params: { - ...params, - mode: "url" - } - }; - }, - createMessage(params) { - return { - method: "sampling/createMessage", - params - }; - }, - listRoots() { - return { method: "roots/list" }; - } -}); -function acceptedContent(responses, key, schema) { - const view = inputResponse(responses, key); - if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; - if (schema === void 0) return view.content; - const outcome = schema["~standard"].validate(view.content); - if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); - return outcome.issues === void 0 ? outcome.value : void 0; -} -/** -* Reads one entry of a retried request's `inputResponses` -* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering -* decline/cancel detection and the non-elicitation response kinds that -* {@linkcode acceptedContent} does not surface. -* -* The values arrive from the client and are not re-validated here — treat -* them as untrusted input (validate elicitation content with the -* schema-aware {@linkcode acceptedContent} overload where it matters). -*/ -function inputResponse(responses, key) { - if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; - const entry = responses[key]; - if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; - const candidate = entry; - if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { - const content = candidate["content"]; - return { - kind: "elicit", - action: candidate["action"], - ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } - }; - } - if (Array.isArray(candidate["roots"])) return { - kind: "roots", - roots: candidate["roots"] - }; - if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { - kind: "sampling", - result: candidate - }; - return { kind: "missing" }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredDriver.ts -/** -* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). -* -* When a request to one of the multi-round-trip methods comes back as -* `input_required`, the driver fulfils the embedded input requests by -* dispatching them to the client's already-registered handlers (elicitation, -* sampling, roots — one generic engine, no per-feature API), then retries the -* original request with the collected `inputResponses` and a byte-exact echo -* of `requestState`, on a fresh request id, until the server returns a -* complete result or the round cap is exhausted. -* -* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the -* same primitive a manual caller uses (`allowInputRequired` semantics — the -* retry hands back the next `input_required` payload instead of recursing), -* so the loop, the cap, and the pacing live in one place and disabling -* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this -* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to -* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by -* shrinking the budget passed to each leg — no new timer system. -*/ -/** -* Fixed pacing applied before retrying a requestState-only (load-shedding) -* leg — a leg that carries no embedded input requests, so nothing slows the -* loop down naturally. Counted in the same round cap. -*/ -const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; -/** -* The message both multi-round-trip loops emit when the round cap is -* exhausted — the client driver as a typed error, the server-side legacy -* shim as its per-family failure. One formatter so the texts cannot drift -* (hosts and models read the tool-result copy verbatim). -*/ -function inputRequiredRoundsExceededMessage(method, maxRounds) { - return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; -} -/** -* Abortable delay: resolves after `ms`, or rejects with the signal's reason -* (wrapped in an `SdkError` when it isn't already one) if the signal aborts -* first. Aborting after resolution is a no-op. Shared with the server-side -* legacy shim (the pacing semantics must match per era). -*/ -function sleep(ms, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); - return; - } - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} -/** -* A per-round abort linked to the caller's signal: the embedded sibling -* dispatches share it, so the first failure (or a caller abort) cancels the -* others instead of leaving them running. Shared with the server-side legacy -* shim (the abort-linkage semantics must match per era). -*/ -function linkedRoundAbort(outer) { - const controller = new AbortController(); - const onOuterAbort = () => controller.abort(outer?.reason); - outer?.addEventListener("abort", onOuterAbort, { once: true }); - if (outer?.aborted) controller.abort(outer.reason); - return { - signal: controller.signal, - abort: (reason) => controller.abort(reason), - dispose: () => outer?.removeEventListener("abort", onOuterAbort) - }; -} - -//#endregion -//#region ../core-internal/src/types/specTypeSchema.ts -/** -* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. -* -* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no -* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, -* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). -* Keeping the list explicit means new public spec types must be added here deliberately, and -* internals never leak into `SpecTypeName`. -* -* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` -* (the bare name collides with the server package's `ResourceTemplate` class), so -* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to -* a type literally named `ResourceTemplate`. -*/ -const SPEC_SCHEMA_KEYS = [ - "AnnotationsSchema", - "AudioContentSchema", - "BaseMetadataSchema", - "BlobResourceContentsSchema", - "BooleanSchemaSchema", - "CallToolRequestSchema", - "CallToolRequestParamsSchema", - "CallToolResultSchema", - "CancelledNotificationSchema", - "CancelledNotificationParamsSchema", - "CancelTaskRequestSchema", - "CancelTaskResultSchema", - "ClientCapabilitiesSchema", - "ClientNotificationSchema", - "ClientRequestSchema", - "ClientResultSchema", - "CompatibilityCallToolResultSchema", - "CompleteRequestSchema", - "CompleteRequestParamsSchema", - "CompleteResultSchema", - "ContentBlockSchema", - "CreateMessageRequestSchema", - "CreateMessageRequestParamsSchema", - "CreateMessageResultSchema", - "CreateMessageResultWithToolsSchema", - "CreateTaskResultSchema", - "CursorSchema", - "DiscoverRequestSchema", - "DiscoverResultSchema", - "ElicitationCompleteNotificationSchema", - "ElicitationCompleteNotificationParamsSchema", - "ElicitRequestSchema", - "ElicitRequestFormParamsSchema", - "ElicitRequestParamsSchema", - "ElicitRequestURLParamsSchema", - "ElicitResultSchema", - "EmbeddedResourceSchema", - "EmptyResultSchema", - "EnumSchemaSchema", - "GetPromptRequestSchema", - "GetPromptRequestParamsSchema", - "GetPromptResultSchema", - "GetTaskPayloadRequestSchema", - "GetTaskPayloadResultSchema", - "GetTaskRequestSchema", - "GetTaskResultSchema", - "IconSchema", - "IconsSchema", - "ImageContentSchema", - "ImplementationSchema", - "InitializedNotificationSchema", - "InitializeRequestSchema", - "InitializeRequestParamsSchema", - "InitializeResultSchema", - "JSONArraySchema", - "JSONObjectSchema", - "JSONRPCErrorResponseSchema", - "JSONRPCMessageSchema", - "JSONRPCNotificationSchema", - "JSONRPCRequestSchema", - "JSONRPCResponseSchema", - "JSONRPCResultResponseSchema", - "JSONValueSchema", - "LegacyTitledEnumSchemaSchema", - "ListPromptsRequestSchema", - "ListPromptsResultSchema", - "ListResourcesRequestSchema", - "ListResourcesResultSchema", - "ListResourceTemplatesRequestSchema", - "ListResourceTemplatesResultSchema", - "ListRootsRequestSchema", - "ListRootsResultSchema", - "ListTasksRequestSchema", - "ListTasksResultSchema", - "ListToolsRequestSchema", - "ListToolsResultSchema", - "LoggingLevelSchema", - "LoggingMessageNotificationSchema", - "LoggingMessageNotificationParamsSchema", - "ModelHintSchema", - "ModelPreferencesSchema", - "MultiSelectEnumSchemaSchema", - "NotificationSchema", - "NumberSchemaSchema", - "PaginatedRequestSchema", - "PaginatedRequestParamsSchema", - "PaginatedResultSchema", - "PingRequestSchema", - "PrimitiveSchemaDefinitionSchema", - "ProgressSchema", - "ProgressNotificationSchema", - "ProgressNotificationParamsSchema", - "ProgressTokenSchema", - "PromptSchema", - "PromptArgumentSchema", - "PromptListChangedNotificationSchema", - "PromptMessageSchema", - "PromptReferenceSchema", - "ReadResourceRequestSchema", - "ReadResourceRequestParamsSchema", - "ReadResourceResultSchema", - "RelatedTaskMetadataSchema", - "RequestSchema", - "RequestIdSchema", - "RequestMetaSchema", - "ResourceSchema", - "ResourceContentsSchema", - "ResourceLinkSchema", - "ResourceListChangedNotificationSchema", - "ResourceRequestParamsSchema", - "ResourceTemplateSchema", - "ResourceTemplateReferenceSchema", - "ResourceUpdatedNotificationSchema", - "ResourceUpdatedNotificationParamsSchema", - "ResultMetaObjectSchema", - "ResultSchema", - "RoleSchema", - "RootSchema", - "RootsListChangedNotificationSchema", - "SamplingContentSchema", - "SamplingMessageSchema", - "SamplingMessageContentBlockSchema", - "ServerCapabilitiesSchema", - "ServerNotificationSchema", - "ServerRequestSchema", - "ServerResultSchema", - "SetLevelRequestSchema", - "SetLevelRequestParamsSchema", - "SingleSelectEnumSchemaSchema", - "StringSchemaSchema", - "SubscribeRequestSchema", - "SubscribeRequestParamsSchema", - "SubscriptionFilterSchema", - "SubscriptionsAcknowledgedNotificationSchema", - "SubscriptionsAcknowledgedNotificationParamsSchema", - "SubscriptionsListenRequestSchema", - "SubscriptionsListenRequestParamsSchema", - "SubscriptionsListenResultSchema", - "SubscriptionsListenResultMetaSchema", - "TaskAugmentedRequestParamsSchema", - "TaskCreationParamsSchema", - "TaskMetadataSchema", - "TaskSchema", - "TaskStatusSchema", - "TaskStatusNotificationSchema", - "TaskStatusNotificationParamsSchema", - "TextContentSchema", - "TextResourceContentsSchema", - "TitledMultiSelectEnumSchemaSchema", - "TitledSingleSelectEnumSchemaSchema", - "ToolSchema", - "ToolAnnotationsSchema", - "ToolChoiceSchema", - "ToolExecutionSchema", - "ToolListChangedNotificationSchema", - "ToolResultContentSchema", - "ToolUseContentSchema", - "UnsubscribeRequestSchema", - "UnsubscribeRequestParamsSchema", - "UntitledMultiSelectEnumSchemaSchema", - "UntitledSingleSelectEnumSchemaSchema" -]; -const authSchemas = { - IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, - OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, - OAuthClientInformationSchema: OAuthClientInformationSchema, - OAuthClientMetadataSchema: OAuthClientMetadataSchema, - OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, - OAuthErrorResponseSchema: OAuthErrorResponseSchema, - OAuthMetadataSchema: OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, - OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, - OAuthTokensSchema: OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, - OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema -}; -const _specTypeSchemas = {}; -const _isSpecType = {}; -function register(key, schema) { - const name = key.slice(0, -6); - _specTypeSchemas[name] = schema; - _isSpecType[name] = (v) => schema.safeParse(v).success; -} -for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); -for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); -/** -* Runtime validators for every MCP spec type, keyed by type name. -* -* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for -* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from -* storage that should be a `Tool`. -* -* Each entry implements the Standard Schema interface, so it composes with any -* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" -* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); -* if (result.issues === undefined) { -* // result.value is CallToolResult -* } -* ``` -*/ -const specTypeSchemas = Object.freeze(_specTypeSchemas); -/** -* Type predicates for every MCP spec type, keyed by type name. -* -* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and -* transforms are applied), and narrows to that input type. For schemas with `.default()` or -* `.preprocess()`, this may accept values that do not structurally match the named output type; -* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use -* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. -* -* Each guard is a standalone function, so it can be passed directly as a callback. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" -* if (isSpecType.ContentBlock(value)) { -* // value is ContentBlock -* } -* -* const blocks = mixed.filter(isSpecType.ContentBlock); -* ``` -*/ -const isSpecType = Object.freeze(_isSpecType); - -//#endregion -//#region ../core-internal/src/wire/bootstrap.ts -function bootstrapOutboundCodec(method) { - switch (method) { - case "initialize": - case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); - case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); - default: return; - } -} - -//#endregion -//#region ../core-internal/src/shared/protocol.ts -/** -* The default request timeout, in milliseconds. -*/ -const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; -/** -* The reserved per-request `_meta` envelope keys (protocol revision -* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before -* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are -* wire-level bookkeeping, not handler material. -*/ -const RESERVED_ENVELOPE_META_KEYS = [ - auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, - auth_CUe6YdwF_CLIENT_INFO_META_KEY, - auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, - LOG_LEVEL_META_KEY -]; -/** -* Top-level params members carrying multi-round-trip driver material -* (protocol revision 2026-07-28). The spec reserves these names on -* client-initiated REQUESTS only — notification params keep them untouched -* (a vendor notification may legitimately use the same names). -*/ -const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; -/** -* Lift wire-only material out of an inbound message so handlers see exactly -* the 2025-era shape, and surface it for the protocol layer (requests: via -* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the -* reserved envelope `_meta` keys are reserved on every message, while the -* multi-round-trip retry fields (`inputResponses`/`requestState`) are -* reserved on client-initiated requests only — so notifications get only the -* envelope lift, and their top-level params stay untouched. Messages without -* wire-only material are returned unchanged (same reference). -*/ -function liftWireOnlyMaterial(message, kind) { - const params = message.params; - if (!isPlainObject$1(params)) return { - message, - lifted: {} - }; - const meta = params._meta; - const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; - const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; - if (envelopeKeys.length === 0 && retryKeys.length === 0) return { - message, - lifted: {} - }; - const lifted = {}; - const nextParams = { ...params }; - if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { - const envelope = {}; - const nextMeta = { ...meta }; - for (const key of envelopeKeys) { - envelope[key] = meta[key]; - delete nextMeta[key]; - } - lifted.envelope = envelope; - if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; - else delete nextParams._meta; - } - for (const key of retryKeys) { - if (key === "inputResponses") lifted.inputResponses = nextParams[key]; - if (key === "requestState") lifted.requestState = nextParams[key]; - delete nextParams[key]; - } - return { - message: { - ...message, - params: nextParams - }, - lifted - }; -} -/** -* Standard Schema adapter over the era codec's `validateResult` function (the -* function-only WireCodec contract exposes no schema objects). Used by the -* spec-method `request()` overload so the request funnel keeps a single -* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema -* paths. -* -* Returns `undefined` when the method has no result entry on this era's -* registry — the caller maps that to the synchronous "pass a result schema" -* TypeError, exactly matching the pre-function-only behavior the -* typedMapAlignment suite pins (the result map deliberately excludes the -* `tasks/*` methods, so the spec-method overload refuses them up front). -*/ -function codecResultValidator(codec, method) { - const probe = codec.validateResult(method, void 0); - if (!probe.ok && probe.reason === "not-in-era") return void 0; - return { "~standard": { - version: 1, - vendor: "mcp-wire-codec", - validate(value) { - const outcome = codec.validateResult(method, value); - if (outcome.ok) return { value: outcome.value }; - return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; - } - } }; -} -/** -* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The -* `as T` below is the one place {@linkcode RequestStateAccessor}'s -* caller-asserted typing is implemented — no implementation can produce an -* arbitrary `T` from a runtime value honestly. -*/ -function requestStateAccessor(value) { - return () => value; -} -/** Shared no-state accessor: the common case allocates nothing per request. */ -const NO_REQUEST_STATE = requestStateAccessor(void 0); -/** -* Returns a context whose `requestState` accessor reads the given value — -* how the server seam hands a verify hook's decoded payload (or the legacy -* shim's per-round echo) to the handler without mutating the original -* context. -*/ -function withRequestStateValue(ctx, value) { - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - requestState: requestStateAccessor(value) - } - }; -} -let writeNegotiatedProtocolVersion; -/** -* Package-internal write channel for a {@linkcode Protocol} instance's -* negotiated protocol version, for callers outside the class hierarchy: -* tests and the (future) modern-era server entry that marks a factory -* instance modern at binding time. Exported on the core internal barrel -* only — never public API. -*/ -function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { - writeNegotiatedProtocolVersion(instance, version); -} -/** -* Implements MCP protocol framing on top of a pluggable transport, including -* features like request/response linking, notifications, and progress. -* -* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific -* implementations most code should use. -*/ -var Protocol = class { - _transport; - _requestMessageId = 0; - _requestHandlers = /* @__PURE__ */ new Map(); - _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - _notificationHandlers = /* @__PURE__ */ new Map(); - _responseHandlers = /* @__PURE__ */ new Map(); - _progressHandlers = /* @__PURE__ */ new Map(); - _timeoutInfo = /* @__PURE__ */ new Map(); - _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); - /** - * The protocol version negotiated for the current connection (`undefined` - * before negotiation completes), which determines the wire era this - * instance speaks. Set by the SDK's negotiation and initialize paths - * (`Client.connect`, `Server._oninitialize`). - */ - _negotiatedProtocolVersion; - static { - writeNegotiatedProtocolVersion = (instance, version) => { - instance._negotiatedProtocolVersion = version; - }; - } - _supportedProtocolVersions; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when {@linkcode Protocol.close | close()} is called as well. - */ - onclose; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler; - constructor(_options) { - this._options = _options; - this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; - this.setNotificationHandler("notifications/cancelled", (notification) => { - this._oncancel(notification); - }); - this.setNotificationHandler("notifications/progress", (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler("ping", (_request) => ({})); - } - /** - * Drop consult for inbound messages whose transport did not classify them - * at the edge — long-lived channels such as stdio, where a role class may - * need to decline traffic the negotiated era has no answer for (the - * client-side inbound-request drop on modern-era connections: the - * 2026-07-28 era has no server→client request channel, and on stdio the - * client must never write JSON-RPC responses). - * - * Consulted ONLY when the transport supplied no - * {@linkcode MessageExtraInfo.classification}: edge-classified traffic - * never reaches the hook. Returning `'drop'` discards the message without - * writing any response (requests are surfaced via `onerror`). The base - * implementation returns `undefined`: unclassified traffic keeps today's - * dispatch path unchanged. Era selection never happens here — era is - * instance state, owned by the serving entry that constructed and - * connected the instance. - */ - _shouldDropInbound(_message) {} - /** - * The per-request `_meta` envelope this instance attaches to every outgoing - * request and notification, when one applies. The base implementation - * returns `undefined` (no envelope — the 2025-era posture, so legacy-era - * outbound traffic is byte-identical to a build without this seam). - * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) - * era to return the reserved protocol-version / client-info / - * client-capabilities keys. User-supplied `_meta` keys take precedence over - * the auto-attached ones. - */ - _outboundMetaEnvelope() {} - /** - * Attach this instance's outbound `_meta` envelope (when one is configured) - * to a request or notification. A no-op when the seam returns `undefined` - * — the message returns by reference, so the legacy-era wire stays - * byte-identical. User-supplied `_meta` keys are spread last so they win - * over the auto-attached envelope keys. - */ - _envelopeOutbound(message) { - const envelope = this._outboundMetaEnvelope(); - if (envelope === void 0) return message; - const params = message.params ?? {}; - return { - ...message, - params: { - ...params, - _meta: { - ...envelope, - ...params._meta - } - } - }; - } - /** - * Extension point for non-`complete` decoded results in the response - * funnel: a result the wire codec discriminated into a kind other than - * `'complete'` or `'invalid'` is handed here for the role class to - * resolve. The base default surfaces it as a typed - * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). - * - * Intended consumers (named so the seam stays accountable): - * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils - * `'input_required'` results through the registered - * elicitation/sampling/roots handlers and retries via `flow.retry`; - * - a future client-side terminal-result handler for - * `subscriptions/listen`, when the spec defines one. - * - * `Server` instances never receive `input_required` responses on their - * outbound legs and leave the base behavior in place. - */ - _resolveNonCompleteResult(decoded, flow) { - return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { - resultType: decoded.kind, - method: flow.request.method - })); - } - /** - * Protected accessor for a registered request handler. Used by role - * classes that dispatch synthesized requests through the same stored - * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip - * input request). - */ - _getRequestHandler(method) { - return this._requestHandlers.get(method); - } - async _oncancel(notification) { - if (!notification.params.requestId) return; - this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - */ - async connect(transport) { - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - try { - _onclose?.(); - } finally { - this._onclose(); - } - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); - else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); - else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); - else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); - }; - transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); - await this._transport.start(); - } - /** - * Transport-close hook. Subclass overrides MUST call `super._onclose()` - * after their own cleanup — base teardown (response-handler settlement, - * timeout clearing, in-flight request abort) does not run otherwise. - */ - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); - this._timeoutInfo.clear(); - const requestHandlerAbortControllers = this._requestHandlerAbortControllers; - this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - try { - this.onclose?.(); - } finally { - for (const handler of responseHandlers.values()) handler(error); - for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - /** - * Inbound-notification dispatch. Subclass overrides MUST delegate - * unmatched traffic to `super._onnotification(rawNotification, extra)` — - * an override that consumes only what it owns and falls through to base - * dispatch for everything else. - */ - _onnotification(rawNotification, extra) { - const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); - return; - } - } - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; - const handler = this._notificationHandlers.get(notification.method); - const fallback = this.fallbackNotificationHandler; - if (handler === void 0 && fallback === void 0) return; - Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(rawRequest, extra) { - const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { - this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); - return; - } - const capturedTransport = this._transport; - const sendErrorResponse = (code, message, data) => { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }; - capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); - }; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); - const requested = extra.classification.revision ?? classified; - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { - supported: this._supportedProtocolVersions, - requested - }); - return; - } - } - if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - if (handler === void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const envelopeError = codec.checkInboundEnvelope(lifted); - if (envelopeError !== void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); - return; - } - const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { - ...options, - relatedRequestId: request.id - }); - const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { - ...options, - relatedRequestId: request.id - }); - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); - const baseCtx = { - sessionId: capturedTransport?.sessionId, - mcpReq: { - id: request.id, - method: request.method, - _meta: request.params?._meta, - ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, - ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, - ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, - requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), - signal: abortController.signal, - send: ((r, schemaOrOptions, maybeOptions) => { - const sendCodec = this._resolveOutboundCodec(r.method); - this._assertOutboundRequestInEra(sendCodec, r.method); - if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(sendCodec, r.method); - if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); - return sendRequest(r, validate, schemaOrOptions); - }), - notify: sendNotification - }, - http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 - }; - const ctx = this.buildContext(baseCtx, extra); - Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { - if (abortController.signal.aborted) return; - let encoded; - try { - encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); - } catch (error) { - this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); - return; - } - const response = { - result: encoded, - jsonrpc: "2.0", - id: request.id - }; - await capturedTransport?.send(response); - }, async (error) => { - if (abortController.signal.aborted) return; - const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: codec.encodeErrorCode(thrownCode), - message: error.message ?? "Internal error", - ...error["data"] !== void 0 && { data: error["data"] } - } - }; - await capturedTransport?.send(errorResponse); - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { - if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { - this._resetTimeout(messageId); - } catch (error) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - handler(params); - } - /** - * Inbound-response dispatch. Subclass overrides MUST delegate unmatched - * traffic to `super._onresponse(response)` — an override that consumes - * only what it owns and falls through to base dispatch for everything - * else. - */ - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === void 0) { - this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._progressHandlers.delete(messageId); - if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); - else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); - } - request(request, schemaOrOptions, maybeOptions) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(codec, request.method); - if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); - return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); - } - /** - * The wire codec for this instance's negotiated era — the phase-2 truth: - * everything an established connection sends and receives resolves - * through it. Legacy until a version has been negotiated. - */ - _negotiatedWireCodec() { - return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - } - /** - * Protected accessor for the instance's negotiated wire codec, for role - * classes (Client/Server/McpServer) routing era-dependent behavior - * through the codec's function-only surface — `samplingResultVariant`, - * `outboundEnvelope`, `projectCallToolResult` — instead of branching on - * the protocol version themselves. - */ - _wireCodec() { - return this._negotiatedWireCodec(); - } - /** - * Outbound codec resolution: while the negotiated version is still unset - * (the negotiation window), lifecycle messages are bootstrap-pinned BY - * METHOD — they self-identify their era (`initialize` IS the legacy - * handshake, `server/discover` IS the modern probe). Once a version has - * been negotiated, the instance era is authoritative for everything — a - * negotiated session never re-routes a method onto the other era. - */ - _resolveOutboundCodec(method) { - if (this._negotiatedProtocolVersion === void 0) { - const pinned = bootstrapOutboundCodec(method); - if (pinned) return pinned; - } - return this._negotiatedWireCodec(); - } - /** - * Era gate for outbound requests — deletions are physical in BOTH - * directions: sending a spec method that the resolved era does not define - * dies locally with a typed error before anything reaches the transport. - * Methods outside the spec universe are consumer-owned extension methods - * and stay era-blind. - */ - _assertOutboundRequestInEra(codec, method) { - if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method, - era: codec.era - }); - } - /** - * Sends a request and waits for a response, using the provided schema for - * validation instead of the era registry's method-keyed entry. - * - * This is the internal implementation used by SDK methods whose result - * schema cannot be expressed as a method-keyed registry entry — the one - * surviving case is `server.createMessage`, whose result schema depends - * on the REQUEST params (tools vs no tools) — and by callers passing - * explicit compatibility schemas. Spec methods are still era-gated here: - * an explicit schema never smuggles a deleted method onto the wire. - */ - _requestWithSchema(request, resultSchema, options) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); - } - /** - * The request funnel proper, keyed by the resolved era codec: the codec - * owns result decoding (raw-first `resultType` discrimination — V-1 — - * and the era's lift posture) before the schema validation step. - */ - _requestWithSchemaViaCodec(codec, request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; - const flowStartedAt = Date.now(); - let onAbort; - let cleanupMessageId; - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(/* @__PURE__ */ new Error("Not connected")); - return; - } - if (this._options?.enforceStrictCapabilities === true) try { - this.assertCapabilityForMethod(request.method); - } catch (error) { - earlyReject(error); - return; - } - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; - const messageId = this._requestMessageId++; - cleanupMessageId = messageId; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...request.params?._meta, - progressToken: messageId - } - }; - } - const outbound = this._envelopeOutbound(jsonrpcRequest); - let responseReceived = false; - const cancel = (reason) => { - if (responseReceived) return; - this._progressHandlers.delete(messageId); - if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }), { - relatedRequestId, - resumptionToken, - onresumptiontoken - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); - else requestAbort.abort(); - reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); - }; - this._responseHandlers.set(messageId, (response) => { - if (options?.signal?.aborted) return; - responseReceived = true; - if (response instanceof Error) return reject(response); - let decoded; - try { - decoded = codec.decodeResult(request.method, response.result); - } catch (error) { - return reject(error instanceof Error ? error : new Error(String(error))); - } - if (decoded.kind === "invalid") return reject(decoded.error); - if (decoded.kind === "input_required") { - if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); - const flow = { - codec, - request, - resultSchema, - options, - flowStartedAt, - retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { - method: request.method, - params - }, resultSchema, legOptions) - }; - return resolve(this._resolveNonCompleteResult(decoded, flow)); - } - const result = decoded.result; - validateStandardSchema(resultSchema, result).then((parseResult) => { - if (parseResult.success) resolve(parseResult.data); - else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); - }, reject); - }); - onAbort = () => cancel(options?.signal?.reason); - options?.signal?.addEventListener("abort", onAbort, { once: true }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - this._transport.send(outbound, { - relatedRequestId, - resumptionToken, - onresumptiontoken, - headers, - requestSignal: requestAbort?.signal - }).catch((error) => { - this._progressHandlers.delete(messageId); - reject(error); - }); - }).finally(() => { - if (onAbort) options?.signal?.removeEventListener("abort", onAbort); - if (cleanupMessageId !== void 0) { - this._responseHandlers.delete(cleanupMessageId); - this._cleanupTimeout(cleanupMessageId); - } - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); - } - /** - * The notification funnel proper, keyed by the resolved era codec — - * direct sends and related notifications (`ctx.mcpReq.notify`) alike - * resolve through the instance's negotiated era at send time. - */ - async _notificationViaCodec(codec, notification, options) { - if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method: notification.method, - era: codec.era - }); - this.assertNotificationCapability(notification.method); - const jsonrpcNotification = this._envelopeOutbound({ - jsonrpc: "2.0", - ...notification - }); - if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { - if (this._pendingDebouncedNotifications.has(notification.method)) return; - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) return; - this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); - }); - return; - } - await this._transport.send(jsonrpcNotification, options); - } - setRequestHandler(method, schemasOrHandler, maybeHandler) { - this.assertRequestHandlerCapability(method); - let stored; - if (typeof schemasOrHandler === "function") { - if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); - stored = (request, ctx) => { - const dispatchCodec = this._negotiatedWireCodec(); - let outcome = dispatchCodec.validateRequest(method, request); - if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value, ctx)); - }; - } else if (maybeHandler) stored = async (request, ctx) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); - return maybeHandler(parsed.data, ctx); - }; - else throw new TypeError("setRequestHandler: handler is required"); - this._requestHandlers.set(method, this._wrapHandler(method, stored)); - } - /** - * Hook for subclasses to wrap a registered request handler with role-specific - * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` - * validates `elicitation/create` mode and result). Runs for both the 2-arg and - * 3-arg registration paths. The default implementation is identity. - * - * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. - */ - _wrapHandler(_method, handler) { - return handler; - } - /** - * Hook for subclasses to supply the implementation identity the 2026-era - * encode seam stamps into outbound result `_meta` under - * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD - * identify themselves on every response). The default is `undefined` — no - * stamp. Only `Server` overrides this: the key identifies the software - * producing a response, and the 2025-era codec never stamps anything - * regardless (the never-stamp guarantee). - */ - _outboundServerInfo() {} - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - setNotificationHandler(method, schemasOrHandler, maybeHandler) { - if (typeof schemasOrHandler === "function") { - if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); - this._notificationHandlers.set(method, (notification, codec) => { - const outcome = codec.validateNotification(method, notification); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value)); - }); - return; - } - if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); - this._notificationHandlers.set(method, async (notification) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); - await maybeHandler(parsed.data, notification); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -}; -function isPlainObject$1(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === void 0) continue; - const baseValue = result[k]; - result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { - ...baseValue, - ...addValue - } : addValue; - } - return result; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredEngine.ts -function src_CX2iR2pK_isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -/** -* Splits a retried request's `inputResponses` map into the BARE response -* entries the spec defines and everything else. The spec's embedded responses -* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or -* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some -* peers emit) is never accepted as a response — its key is recorded so the -* handler can re-issue the corresponding input request. -*/ -function partitionInputResponses(inputResponses) { - const accepted = {}; - const droppedKeys = []; - if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { - accepted, - droppedKeys - }; - for (const [key, entry] of Object.entries(inputResponses)) { - if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { - droppedKeys.push(key); - continue; - } - accepted[key] = entry; - } - return { - accepted, - droppedKeys - }; -} -/** -* Builds the manual-mode {@linkcode InputRequiredResult} value from the -* codec's decoded payload — what an `allowInputRequired: true` caller -* receives instead of the auto-fulfilled complete result. -*/ -function manualInputRequiredValue(decoded) { - return { - resultType: "input_required", - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; -} - -//#endregion -//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js -/*! -* content-type -* Copyright(c) 2015 Douglas Christopher Wilson -* MIT Licensed -*/ -var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { - /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.parse = parse; - /** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - function parse(string) { - if (!string) throw new TypeError("argument string is required"); - var header = typeof string === "object" ? getcontenttype(string) : string; - if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); - var index = header.indexOf(";"); - var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); - var obj = new ContentType(type.toLowerCase()); - if (index !== -1) { - var key; - var match; - var value; - PARAM_REGEXP.lastIndex = index; - while (match = PARAM_REGEXP.exec(header)) { - if (match.index !== index) throw new TypeError("invalid parameter format"); - index += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value.charCodeAt(0) === 34) { - value = value.slice(1, -1); - if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); - } - obj.parameters[key] = value; - } - if (index !== header.length) throw new TypeError("invalid parameter format"); - } - return obj; - } - /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - function getcontenttype(obj) { - var header; - if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); - else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; - if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); - return header; - } - /** - * Class to represent a content type. - * @private - */ - function ContentType(type) { - this.parameters = Object.create(null); - this.type = type; - } -})); - -//#endregion -//#region ../core-internal/src/shared/mediaType.ts -var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); -/** -* Extracts the media type (the lowercased `type/subtype` pair, without -* parameters) from a raw `Content-Type` header value, or `undefined` when the -* header is missing or empty. -* -* Content-Type comparisons must use the parsed media type, never a substring -* search of the raw header: a value like `text/plain; a=application/json` -* contains the substring `application/json` but its media type is -* `text/plain`, and case variants or parameters make naive string comparison -* wrong in both directions. -* -* "Essence" is the WHATWG MIME Sniffing standard's term for the bare -* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); -* the Fetch standard's request classification is defined against it -* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). -* -* Parsing is RFC 9110 (`content-type` package) first. When the parameter -* section is malformed (`application/json;`, `application/json; charset=`), -* browsers and most HTTP stacks still derive the media type from the segment -* before the first `;` — the fallback matches that widely-implemented -* behavior, so a header whose media type is unambiguous is not rejected for -* a sloppy parameter section. -*/ -function src_CX2iR2pK_mediaTypeEssence(header) { - if (!header) return; - try { - return import_content_type.parse(header).type; - } catch { - const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); - if (essence === "" || header.slice(essence.length).includes(",")) return; - return essence; - } -} -/** -* Whether a raw `Content-Type` header value denotes `application/json`. -* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed -* parameter sections do not reject a header whose media type is unambiguously -* `application/json` (see `mediaTypeEssence` for the exact grammar). -*/ -function src_CX2iR2pK_isJsonContentType(header) { - if (header === "application/json") return true; - return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; -} - -//#endregion -//#region ../core-internal/src/shared/metadataUtils.ts -/** -* Utilities for working with {@linkcode BaseMetadata} objects. -*/ -/** -* Gets the display name for an object with {@linkcode BaseMetadata}. -* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` -* For other objects: `title` → `name` -* This implements the spec requirement: "if no title is provided, name should be used for display purposes" -*/ -function getDisplayName(metadata) { - if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; - if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; - return metadata.name; -} - -//#endregion -//#region ../core-internal/src/shared/stdio.ts -const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; -/** -* Buffers a continuous stdio stream into discrete JSON-RPC messages. -*/ -var ReadBuffer = class { - _buffer; - _maxBufferSize; - constructor(options) { - this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; - } - append(chunk) { - if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { - this.clear(); - throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); - } - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - while (this._buffer) { - const index = this._buffer.indexOf("\n"); - if (index === -1) return null; - const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); - this._buffer = this._buffer.subarray(index + 1); - try { - return deserializeMessage(line); - } catch (error) { - if (error instanceof SyntaxError) continue; - throw error; - } - } - return null; - } - clear() { - this._buffer = void 0; - } -}; -function deserializeMessage(line) { - return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + "\n"; -} - -//#endregion -//#region ../core-internal/src/shared/toolNameValidation.ts -/** -* Tool name validation utilities according to SEP: Specify Format for Tool Names -* -* Tool names SHOULD be between 1 and 128 characters in length (inclusive). -* Tool names are case-sensitive. -* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits -* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). -* Tool names SHOULD NOT contain spaces, commas, or other special characters. -* -* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} -*/ -/** -* Regular expression for valid tool names according to SEP-986 specification -*/ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** -* Validates a tool name according to the SEP specification -* @param name - The tool name to validate -* @returns An object containing validation result and any warnings -*/ -function validateToolName(name) { - const warnings = []; - if (name.length === 0) return { - isValid: false, - warnings: ["Tool name cannot be empty"] - }; - if (name.length > 128) return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); - if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); - if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); - if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** -* Issues warnings for non-conforming tool names -* @param name - The tool name that triggered the warnings -* @param warnings - Array of warning messages -*/ -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) console.warn(` - ${warning}`); - console.warn("Tool registration will proceed, but this may cause compatibility issues."); - console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); - console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); - } -} -/** -* Validates a tool name and issues warnings for non-conforming names -* @param name - The tool name to validate -* @returns `true` if the name is valid, `false` otherwise -*/ -function validateAndWarnToolName(name) { - const result = validateToolName(name); - issueToolNameWarning(name, result.warnings); - return result.isValid; -} - -//#endregion -//#region ../core-internal/src/shared/transport.ts -/** -* Normalizes `HeadersInit` to a plain `Record` for manipulation. -* Handles `Headers` objects, arrays of tuples, and plain objects. -*/ -function normalizeHeaders(headers) { - if (!headers) return {}; - if (headers instanceof Headers) return Object.fromEntries(headers.entries()); - if (Array.isArray(headers)) return Object.fromEntries(headers); - return { ...headers }; -} -/** -* Creates a fetch function that includes base `RequestInit` options. -* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. -* -* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) -* @param baseInit - The base `RequestInit` to merge with each request -* @returns A wrapped fetch function that merges base options with call-specific options -*/ -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) return baseFetch; - return async (url, init) => { - return baseFetch(url, { - ...baseInit, - ...init, - headers: init?.headers ? { - ...normalizeHeaders(baseInit.headers), - ...normalizeHeaders(init.headers) - } : baseInit.headers - }); - }; -} - -//#endregion -//#region ../core-internal/src/shared/uriTemplate.ts -const MAX_TEMPLATE_LENGTH = 1e6; -const MAX_VARIABLE_LENGTH = 1e6; -const MAX_TEMPLATE_EXPRESSIONS = 1e4; -const MAX_REGEX_LENGTH = 1e6; -var src_CX2iR2pK_UriTemplate = class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like `{foo}` or `{?bar}`. - */ - static isTemplate(str) { - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - template; - parts; - get variableNames() { - return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ""; - let i = 0; - let expressionCount = 0; - while (i < template.length) if (template[i] === "{") { - if (currentText) { - parts.push(currentText); - currentText = ""; - } - const end = template.indexOf("}", i); - if (end === -1) throw new Error("Unclosed template expression"); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes("*"); - const names = this.getNames(expr); - const name = names[0]; - for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - parts.push({ - name, - operator, - names, - exploded - }); - i = end + 1; - } else { - currentText += template[i]; - i++; - } - if (currentText) parts.push(currentText); - return parts; - } - getOperator(expr) { - return [ - "+", - "#", - ".", - "/", - "?", - "&" - ].find((op) => expr.startsWith(op)) || ""; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); - if (operator === "+" || operator === "#") return encodeURI(value); - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === "?" || part.operator === "&") { - const pairs = part.names.map((name) => { - const value$1 = variables[name]; - if (value$1 === void 0) return ""; - return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; - }).filter((pair) => pair.length > 0); - if (pairs.length === 0) return ""; - return (part.operator === "?" ? "?" : "&") + pairs.join("&"); - } - if (part.names.length > 1) { - const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); - if (values.length === 0) return ""; - return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); - } - const value = variables[part.name]; - if (value === void 0) return ""; - const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); - switch (part.operator) { - case "": return encoded.join(","); - case "+": return encoded.join(","); - case "#": return "#" + encoded.join(","); - case ".": return "." + encoded.join("."); - case "/": return "/" + encoded.join("/"); - default: return encoded.join(","); - } - } - expand(variables) { - let result = ""; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === "string") { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) continue; - result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; - if (part.operator === "?" || part.operator === "&") hasQueryParam = true; - } - return result; - } - escapeRegExp(str) { - return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); - } - partToRegExp(part) { - const patterns = []; - for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - if (part.operator === "?" || part.operator === "&") { - for (let i = 0; i < part.names.length; i++) { - const name$1 = part.names[i]; - const prefix = i === 0 ? "\\" + part.operator : "&"; - patterns.push({ - pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", - name: name$1 - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case "": - pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; - break; - case "+": - case "#": - pattern = "(.+)"; - break; - case ".": - pattern = String.raw`\.([^/,]+)`; - break; - case "/": - pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); - break; - default: pattern = "([^/]+)"; - } - patterns.push({ - pattern, - name - }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); - let pattern = "^"; - const names = []; - for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ - name, - exploded: part.exploded - }); - } - } - pattern += "$"; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) return null; - const result = {}; - for (const [i, name_] of names.entries()) { - const { name, exploded } = name_; - const value = match[i + 1]; - const cleanName = name.replace("*", ""); - result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; - } - return result; - } -}; - -//#endregion -//#region ../core-internal/src/util/inMemory.ts -/** -* In-memory transport for creating clients and servers that talk to each other within the same process. -* -* Intended for testing and development. For production in-process connections, use -* `StreamableHTTPClientTransport` against a local server URL. -*/ -var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { - _otherTransport; - _messageQueue = []; - _closed = false; - onclose; - onerror; - onmessage; - sessionId; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - this.onmessage?.(queuedMessage.message, queuedMessage.extra); - } - } - async close() { - if (this._closed) return; - this._closed = true; - const other = this._otherTransport; - this._otherTransport = void 0; - try { - await other?.close(); - } finally { - this.onclose?.(); - } - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); - else this._otherTransport._messageQueue.push({ - message, - extra: { authInfo: options?.authInfo } - }); - } -}; - -//#endregion -//#region ../core-internal/src/util/zodCompat.ts -/** -* Zod-specific helpers for the v1-compat raw-shape shorthand on -* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so -* that file stays library-agnostic per the Standard Schema spec. -*/ -function isZodV4Schema(v) { - return typeof v === "object" && v !== null && "_zod" in v; -} -function looksLikeZodV3(v) { - return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; -} -/** -* Detects a "raw shape" — a plain object whose values are Zod field schemas, -* e.g. `{ name: z.string() }`. Powers the auto-wrap in -* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only -* Zod values are supported. -* -* @internal -*/ -function isZodRawShape(obj) { - if (typeof obj !== "object" || obj === null) return false; - if (isStandardSchema(obj)) return false; - const proto = Object.getPrototypeOf(obj); - if (proto !== Object.prototype && proto !== null) return false; - return Object.values(obj).every((v) => isZodV4Schema(v)); -} -/** -* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape -* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. -* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a -* uniform schema type; already-wrapped schemas pass through unchanged. -* -* @internal -*/ -function normalizeRawShapeSchema(schema) { - if (schema === void 0) return void 0; - if (isZodRawShape(schema)) return schemas_object(schema); - if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); - if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); - return schema; -} - -//#endregion -//#region ../core-internal/src/wire/preload.ts -/** -* Explicit warm-up entry for the lazy wire-schema layers. -* -* The per-revision wire schemas are built lazily: each era's schema set sits -* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the -* registry/codec lookup maps above those factories are memoized the same way. -* That laziness is the right default on process-per-invocation runtimes (CLI -* tools, dev servers), where module evaluation IS startup latency and most -* short-lived processes never validate a message on both eras. -* -* On platforms that bill request CPU but not module evaluation — isolate-based -* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: -* module-scope work runs during isolate warm-up outside any request, while -* lazy construction lands inside the first request's billed (and latency -* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move -* the one-time construction cost back to module scope by calling it at module -* scope themselves. The packages' own workerd shims already do this, so -* Workers deployments get eager construction automatically. -*/ -/** -* Eagerly builds every lazily-constructed wire-schema layer, so that no later -* validation pays schema-construction cost. -* -* Synchronous and idempotent: every layer is a memo, so the first call does -* all the work and subsequent calls return immediately. Reference identity is -* unaffected — this forces the same memos every lazy consumer pulls through. -* -* Call it at module scope on platforms that bill per-request CPU but not -* module evaluation (isolate-based edge/serverless runtimes), where deferring -* construction would move it into the first request of every fresh isolate: -* -* ```ts -* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — -* // each package bundles its own schema copy, so warm the one(s) you import. -* preloadSchemas(); // module scope — runs during isolate warm-up -* ``` -* -* On Node CLIs and other process-per-invocation runtimes, prefer the lazy -* default — there, module-scope construction is pure added boot latency. -*/ -function preloadSchemas() { - buildSchemas2025(); - buildSchemas2026(); - warmRegistryMaps2025(); - warmInputSchemaMaps2026(); - warmWireResultSchemas2026(); -} - -//#endregion -//#region ../core-internal/src/validators/fromJsonSchema.ts -/** -* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be -* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON -* Schema (e.g. from TypeBox, or hand-written) and want to register it without going -* through a Standard Schema library. -* -* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript -* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. -* -* @param schema - A JSON Schema object describing the expected shape -* @param validator - A validator provider. When importing `fromJsonSchema` from -* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate -* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). -* -* @example -* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" -* const inputSchema = fromJsonSchema<{ name: string }>( -* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, -* validator -* ); -* // Use with server.registerTool('greet', { inputSchema }, handler) -* ``` -*/ -function fromJsonSchema(schema, validator) { - const check = validator.getValidator(schema); - return { "~standard": { - version: 1, - vendor: "mcp", - jsonSchema: { - input: () => schema, - output: () => schema - }, - validate: (data) => { - const result = check(data); - return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; - } - } }; -} - -//#endregion - -//# sourceMappingURL=src-CX2iR2pK.mjs.map - - - -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class {}; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name = class extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) return false; - const item = this._items[0]; - return item === "" || item === "\"\""; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - const plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) code.push(...arg._items); - else if (arg instanceof Name) code.push(arg); - else code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === "\"\"") return a; - if (a === "\"\"") return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== "\"") return; - if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; - if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - const code_1 = require_code$1(); - var ValueError = class extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - }; - var UsedValueState; - (function(UsedValueState) { - UsedValueState[UsedValueState["Started"] = 0] = "Started"; - UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - return this._names[prefix] = { - prefix, - index: 0 - }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - const line = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { - ...opts, - _n: opts.lines ? line : code_1.nil - }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) return _name; - } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { - property: prefix, - itemIndex - }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; - else throw new ValueError(name); - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - }; - exports.ValueScope = ValueScope; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - const code_1 = require_code$1(); - const scope_1 = require_scope(); - var code_2 = require_code$1(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return code_2._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return code_2.str; - } - }); - Object.defineProperty(exports, "strConcat", { - enumerable: true, - get: function() { - return code_2.strConcat; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return code_2.nil; - } - }); - Object.defineProperty(exports, "getProperty", { - enumerable: true, - get: function() { - return code_2.getProperty; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return code_2.stringify; - } - }); - Object.defineProperty(exports, "regexpCode", { - enumerable: true, - get: function() { - return code_2.regexpCode; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return code_2.Name; - } - }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function() { - return scope_2.Scope; - } - }); - Object.defineProperty(exports, "ValueScope", { - enumerable: true, - get: function() { - return scope_2.ValueScope; - } - }); - Object.defineProperty(exports, "ValueScopeName", { - enumerable: true, - get: function() { - return scope_2.ValueScopeName; - } - }); - Object.defineProperty(exports, "varKinds", { - enumerable: true, - get: function() { - return scope_2.varKinds; - } - }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) return; - if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - }; - var Assign = class extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); - } - }; - var AssignOp = class extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - }; - var Label = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - }; - var Break = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `break${this.label ? ` ${this.label}` : ""};` + _n; - } - }; - var Throw = class extends Node { - constructor(error) { - super(); - this.error = error; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - }; - var AnyCode = class extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - }; - var ParentNode = class extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) nodes.splice(i, 1, ...n); - else if (n) nodes[i] = n; - else nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - }; - var BlockNode = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode {}; - var Else = class extends BlockNode {}; - Else.kind = "else"; - var If = class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) return e instanceof If ? e : e.nodes; - if (this.nodes.length) return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) return void 0; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) addNames(names, this.else.names); - return names; - } - }; - If.kind = "if"; - var For = class extends BlockNode {}; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - }; - var ForRange = class extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - return addExprNames(addExprNames(super.names, this.from), this.to); - } - }; - var ForIter = class extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - }; - var Func = class extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); - } - }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - }; - Return.kind = "return"; - var Try = class extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) code += this.catch.render(opts); - if (this.finally) code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) addNames(names, this.catch.names); - if (this.finally) addNames(names, this.finally.names); - return names; - } - }; - var Catch = class extends BlockNode { - constructor(error) { - super(); - this.error = error; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { - ...opts, - _n: opts.lines ? "\n" : "" - }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") c(); - else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); - else if (thenBody) this.code(thenBody).endIf(); - else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error = this.name("e"); - this._currNode = node.catch = new Catch(error); - catchCode(error); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error) { - return this._leafNode(new Throw(error)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) return replaceName(expr); - if (!canOptimize(expr)) return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) c = replaceName(c); - if (c instanceof code_1._Code) items.push(...c._items); - else items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - const andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - const orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - const codegen_1 = require_codegen(); - const code_1 = require_code$1(); - function toHash(arr) { - const hash = {}; - for (const item of arr) hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") return schema; - if (Object.keys(schema).length === 0) return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self } = it; - if (!opts.strictSchema) return; - if (typeof schema === "boolean") return; - const rules = self.RULES.keywords; - for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (rules[key]) return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") return schema; - if (typeof schema == "string") return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) for (const x of xs) f(x); - else f(xs); - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) gen.assign(to, true); - else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { - ...from, - ...to - }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - const snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type) { - Type[Type["Num"] = 0] = "Num"; - Type[Type["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) return; - msg = `strict mode: ${msg}`; - if (mode === true) throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; - exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); - else returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - exports.reportError = reportError; - function reportExtraError(cxt, error = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - addError(gen, errorObjectCode(cxt, error, errorPaths)); - if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - /* istanbul ignore if */ - if (errsCount === void 0) throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - const E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error, errorPaths); - } - function errorObject(cxt, error, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; - extraErrorProps(cxt, error, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - if (propertyName) keyValues.push([E.propertyName, propertyName]); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const boolError = { message: "boolean schema is false" }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) falseSchemaError(it, false); - else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else gen.var(valid, true); - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - const jsonTypes = new Set([ - "string", - "number", - "integer", - "boolean", - "null", - "object", - "array" - ]); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { - type: "number", - rules: [] - }, - string: { - type: "string", - rules: [] - }, - array: { - type: "array", - rules: [] - }, - object: { - type: "object", - rules: [] - } - }; - return { - types: { - ...groups, - integer: true, - boolean: true, - null: true - }, - rules: [ - { rules: [] }, - groups.number, - groups.string, - groups.array, - groups.object - ], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self }, type) { - const group = self.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - const rules_1 = require_rules(); - const applicability_1 = require_applicability(); - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - var DataType; - (function(DataType) { - DataType[DataType["Correct"] = 0] = "Correct"; - DataType[DataType["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - if (types.includes("null")) { - if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); - if (schema.nullable === true) types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) coerceData(it, types, coerceTo); - else reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - const COERCIBLE = new Set([ - "string", - "number", - "integer", - "boolean", - "null" - ]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else cond = codegen_1.nil; - if (types.number) delete types.integer; - for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - const typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); - else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - const newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const code_1 = require_code(); - const errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a$1; - gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { - ref: result, - code: (0, codegen_1.stringify)(result) - }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { - /* istanbul ignore if */ - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - if (def.validateSchema) { - if (!def.validateSchema(schema[keyword])) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") self.logger.error(msg); - else throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error("either \"keyword\" or \"schema\" must be passed"); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); - if (propertyName !== void 0) subschema.propertyName = propertyName; - } - if (dataTypes) subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) subschema.compositeRule = compositeRule; - if (createErrors !== void 0) subschema.createErrors = createErrors; - if (allErrors !== void 0) subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0;) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { - var traverse = module.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - const util_1 = require_util(); - const equal = require_fast_deep_equal(); - const traverse = require_json_schema_traverse(); - const SIMPLE_INLINED = new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") return true; - if (limit === true) return !hasRef(schema); - if (!limit) return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - const REF_KEYWORDS = new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) return true; - if (typeof sch == "object" && hasRef(sch)) return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) continue; - if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - if (count === Infinity) return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) id = normalizeId(id); - return _getFullPath(resolver, resolver.parse(id)); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - return resolver.serialize(p).split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - const TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); - else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else this.refs[ref] = fullPath; - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); - } - function ambiguos(ref) { - return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - const boolSchema_1 = require_boolSchema(); - const dataType_1 = require_dataType(); - const applicability_1 = require_applicability(); - const dataType_2 = require_dataType(); - const defaults_1 = require_defaults(); - const keyword_1 = require_keyword(); - const subschema_1 = require_subschema(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self }) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (self.RULES.all[key]) return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self } = it; - const { RULES } = self; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else iterateKeywords(it, group); - if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); - else if (withTypes.includes("integer") && t === "number") ts.push("integer"); - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) failAction(); - else this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) this.gen.endIf(); - } else if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - fail$data(condition) { - if (!this.$data) return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) Object.assign(this.params, obj); - else this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - /* istanbul ignore if */ - if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { - ...this.it, - ...subschema, - items: void 0, - props: void 0 - }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) return; - if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) def.code(cxt, ruleType); - else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); - else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - } - const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - }; - exports.default = ValidationError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - }; - exports.default = MissingRefError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - const codegen_1 = require_codegen(); - const validation_error_1 = require_validation_error(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { - es5, - lines, - ownProperties - }); - let _ValidationError; - if (sch.$async) _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { - ref: sch.schema, - code: (0, codegen_1.stringify)(sch.schema) - } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); - const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) validate.$async = true; - if (this.opts.code.source === true) validate.source = { - validateName, - validateCode, - scopeValues: gen._values - }; - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) return schOrFunc; - let _sch = resolve.call(this, root, ref); - if (_sch === void 0) { - const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) _sch = new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - if (_sch === void 0) return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; - if (!schOrRef.validate) compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - const PREVENT_SCOPE_CHANGE = new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - if (env.schema !== env.root.schema) return env; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", - "type": "object", - "required": ["$data"], - "properties": { "$data": { - "type": "string", - "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] - } }, - "additionalProperties": false - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { - /** @type {(value: string) => boolean} */ - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - /** @type {(value: string) => boolean} */ - const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); - /** - * @param {Array} input - * @returns {string} - */ - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (code === 48) continue; - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - break; - } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - } - return acc; - } - /** - * @typedef {Object} GetIPV6Result - * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. - * @property {string} address - The parsed IPv6 address. - * @property {string} [zone] - The zone identifier, if present. - */ - /** - * @param {string} value - * @returns {boolean} - */ - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - /** - * @param {Array} buffer - * @returns {boolean} - */ - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - /** - * @param {Array} buffer - * @param {Array} address - * @param {GetIPV6Result} output - * @returns {boolean} - */ - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== "") address.push(hex); - else { - output.error = true; - return false; - } - buffer.length = 0; - } - return true; - } - /** - * @param {string} input - * @returns {GetIPV6Result} - */ - function getIPV6(input) { - let tokenCount = 0; - const output = { - error: false, - address: "", - zone: "" - }; - /** @type {Array} */ - const address = []; - /** @type {Array} */ - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === "[" || cursor === "]") continue; - if (cursor === ":") { - if (endipv6Encountered === true) endIpv6 = true; - if (!consume(buffer, address, output)) break; - if (++tokenCount > 7) { - output.error = true; - break; - } - if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; - address.push(":"); - continue; - } else if (cursor === "%") { - if (!consume(buffer, address, output)) break; - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue; - } - } - if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); - else if (endIpv6) address.push(buffer.join("")); - else address.push(stringArrayToHexStripped(buffer)); - output.address = address.join(""); - return output; - } - /** - * @typedef {Object} NormalizeIPv6Result - * @property {string} host - The normalized host. - * @property {string} [escapedHost] - The escaped host. - * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. - */ - /** - * @param {string} host - * @returns {NormalizeIPv6Result} - */ - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) return { - host, - isIPV6: false - }; - const ipv6 = getIPV6(host); - if (!ipv6.error) { - let newHost = ipv6.address; - let escapedHost = ipv6.address; - if (ipv6.zone) { - newHost += "%" + ipv6.zone; - escapedHost += "%25" + ipv6.zone; - } - return { - host: newHost, - isIPV6: true, - escapedHost - }; - } else return { - host, - isIPV6: false - }; - } - /** - * @param {string} str - * @param {string} token - * @returns {number} - */ - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; - return ind; - } - /** - * @param {string} path - * @returns {string} - * - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 - */ - function removeDotSegments(path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) if (input === ".") break; - else if (input === "/") { - output.push("/"); - break; - } else { - output.push(input); - break; - } - else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") break; - else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) output.pop(); - output.push("/"); - break; - } - } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; - } - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) output.pop(); - continue; - } - } - } - } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join(""); - } - /** - * @param {import('../types/index').URIComponent} component - * @param {boolean} esc - * @returns {import('../types/index').URIComponent} - */ - function normalizeComponentEncoding(component, esc) { - const func = esc !== true ? escape : unescape; - if (component.scheme !== void 0) component.scheme = func(component.scheme); - if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); - if (component.host !== void 0) component.host = func(component.host); - if (component.path !== void 0) component.path = func(component.path); - if (component.query !== void 0) component.query = func(component.query); - if (component.fragment !== void 0) component.fragment = func(component.fragment); - return component; - } - /** - * @param {import('../types/index').URIComponent} component - * @returns {string|undefined} - */ - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; - else host = component.host; - } - uriTokens.push(host); - } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { isUUID } = require_utils(); - const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - const supportedSchemeNames = [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ]; - /** @typedef {supportedSchemeNames[number]} SchemeName */ - /** - * @param {string} name - * @returns {name is SchemeName} - */ - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf(name) !== -1; - } - /** - * @callback SchemeFn - * @param {import('../types/index').URIComponent} component - * @param {import('../types/index').Options} options - * @returns {import('../types/index').URIComponent} - */ - /** - * @typedef {Object} SchemeHandler - * @property {SchemeName} scheme - The scheme name. - * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. - * @property {SchemeFn} parse - Function to parse the URI component for this scheme. - * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. - * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. - * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. - * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. - */ - /** - * @param {import('../types/index').URIComponent} wsComponent - * @returns {boolean} - */ - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) return true; - else if (wsComponent.secure === false) return false; - else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - else return false; - } - /** @type {SchemeFn} */ - function httpParse(component) { - if (!component.host) component.error = component.error || "HTTP URIs must have a host."; - return component; - } - /** @type {SchemeFn} */ - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; - if (!component.path) component.path = "/"; - return component; - } - /** @type {SchemeFn} */ - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path && path !== "/" ? path : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); - urnComponent.path = void 0; - if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); - } else urnComponent.error = urnComponent.error || "URN can not be parsed."; - return urnComponent; - } - /** @type {SchemeFn} */ - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); - if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - /** @type {SchemeFn} */ - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; - return uuidComponent; - } - /** @type {SchemeFn} */ - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - const http = { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }; - const https = { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - }; - const ws = { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }; - const wss = { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }; - const urn = { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }; - const urnuuid = { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }; - const SCHEMES = { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - }; - Object.setPrototypeOf(SCHEMES, null); - /** - * @param {string|undefined} scheme - * @returns {SchemeHandler|undefined} - */ - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - const { SCHEMES, getSchemeHandler } = require_schemes(); - /** - * @template {import('./types/index').URIComponent|string} T - * @param {T} uri - * @param {import('./types/index').Options} [options] - * @returns {T} - */ - function normalize(uri, options) { - if (typeof uri === "string") uri = serialize(parse(uri, options), options); - else if (typeof uri === "object") uri = parse(serialize(uri, options), options); - return uri; - } - /** - * @param {string} baseURI - * @param {string} relativeURI - * @param {import('./types/index').Options} [options] - * @returns {string} - */ - function resolve(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - /** - * @param {import ('./types/index').URIComponent} base - * @param {import ('./types/index').URIComponent} relative - * @param {import('./types/index').Options} [options] - * @param {boolean} [skipNormalization=false] - * @returns {import ('./types/index').URIComponent} - */ - function resolveComponent(base, relative, options, skipNormalization) { - /** @type {import('./types/index').URIComponent} */ - const target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== void 0) target.query = relative.query; - else target.query = base.query; - } else { - if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); - else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; - else if (!base.path) target.path = relative.path; - else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; - } - /** - * @param {import ('./types/index').URIComponent|string} uriA - * @param {import ('./types/index').URIComponent|string} uriB - * @param {import ('./types/index').Options} options - * @returns {boolean} - */ - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { - ...options, - skipEscape: true - }); - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { - ...options, - skipEscape: true - }); - return uriA.toLowerCase() === uriB.toLowerCase(); - } - /** - * @param {Readonly} cmpts - * @param {import('./types/index').Options} [opts] - * @returns {string} - */ - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); - } else component.path = unescape(component.path); - if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") uriTokens.push("//"); - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") uriTokens.push("/"); - } - if (component.path !== void 0) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); - if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); - uriTokens.push(s); - } - if (component.query !== void 0) uriTokens.push("?", component.query); - if (component.fragment !== void 0) uriTokens.push("#", component.fragment); - return uriTokens.join(""); - } - const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - /** - * @param {string} uri - * @param {import('./types/index').Options} [opts] - * @returns - */ - function parse(uri, opts) { - const options = Object.assign({}, opts); - /** @type {import('./types/index').URIComponent} */ - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP = false; - if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; - else uri = "//" + uri; - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) parsed.port = matches[5]; - if (parsed.host) if (isIPv4(parsed.host) === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else isIP = true; - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; - else if (parsed.scheme === void 0) parsed.reference = "relative"; - else if (parsed.fragment === void 0) parsed.reference = "absolute"; - else parsed.reference = "uri"; - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); - if (parsed.host !== void 0) parsed.host = unescape(parsed.host); - } - if (parsed.path) parsed.path = escape(unescape(parsed.path)); - if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); - } else parsed.error = parsed.error || "URI can not be parsed."; - return parsed; - } - const fastUri = { - SCHEMES, - normalize, - resolve, - resolveComponent, - equal, - serialize, - parse - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const uri = require_fast_uri(); - uri.code = "require(\"ajv/dist/runtime/uri\").default"; - exports.default = uri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - const validation_error_1 = require_validation_error(); - const ref_error_1 = require_ref_error(); - const rules_1 = require_rules(); - const compile_1 = require_compile(); - const codegen_2 = require_codegen(); - const resolve_1 = require_resolve(); - const dataType_1 = require_dataType(); - const util_1 = require_util(); - const $dataRefSchema = require_data(); - const uri_1 = require_uri(); - const defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - const META_IGNORE_OPTIONS = [ - "removeAdditional", - "useDefaults", - "coerceTypes" - ]; - const EXT_SCOPE_NAMES = new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - const removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: "\"nullable\" keyword is supported by default.", - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: "\"uniqueItems\" keyword is always validated.", - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now." - }; - const deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." - }; - const MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { - ...o.code, - optimize, - regExp - } : { - optimize, - regExp - }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { - ...opts, - ...requiredOptions(opts) - }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ - scope: {}, - prefixes: EXT_SCOPE_NAMES, - es5, - lines - }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else v = this.compile(schemaKeyRef); - const valid = v(data); - if (!("$async" in v)) this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") this.logger.error(message); - else throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ - schema: {}, - schemaId - }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); - } else throw new Error("invalid addKeywords parameters"); - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) return "No errors"; - return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") delete schemas[keyRef]; - else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") id = schema[schemaId]; - else if (this.opts.jtd) throw new Error("schema must be object"); - else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); - let sch = this._cache.get(schema); - if (sch !== void 0) return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ - schema, - schemaId, - meta, - baseId, - localRefs - }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); - } - _compileSchemaEnv(sch) { - if (sch.meta) this._compileMetaSchema(sch); - else compile_1.compileSchema.call(this, sch); - /* istanbul ignore if */ - if (!sch.validate) throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); - else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; - return metaOpts; - } - const noLogs = { - log() {}, - warn() {}, - error() {} - }; - function getLogger(logger) { - if (logger === false) return noLogs; - if (logger === void 0) return console; - if (logger.log && logger.warn && logger.error) return logger; - throw new Error("logger must implement log, warn and error methods"); - } - const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) return; - if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { - type: dataType, - rules: [] - }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); - else ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) ruleGroup.rules.splice(i, 0, rule); - else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) return; - if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "id", - code() { - throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - const ref_error_1 = require_ref_error(); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const util_1 = require_util(); - const def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); - if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - callRef(cxt, getValidate(cxt, sch), sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { - ref: sch, - code: (0, codegen_1.stringify)(sch) - } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) callAsyncRef(); - else callSyncRef(); - function callAsyncRef() { - if (!env.$async) throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - exports.callRef = callRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const id_1 = require_id(); - const ref_1 = require_ref(); - const core = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - maximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - minimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - exclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - exclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const ucs2length_1 = require_ucs2length(); - const def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const util_1 = require_util(); - const codegen_1 = require_codegen(); - const def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) allErrorsMode(); - else exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - function allErrorsMode() { - if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); - else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const equal = require_fast_deep_equal(); - equal.code = "require(\"ajv/dist/runtime/equal\").default"; - exports.default = equal; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dataType_1 = require_dataType(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ - i, - j - }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "const", - $data: true, - error: { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const limitNumber_1 = require_limitNumber(); - const multipleOf_1 = require_multipleOf(); - const limitLength_1 = require_limitLength(); - const pattern_1 = require_pattern(); - const limitProperties_1 = require_limitProperties(); - const required_1 = require_required(); - const limitItems_1 = require_limitItems(); - const uniqueItems_1 = require_uniqueItems(); - const const_1 = require_const(); - const enum_1 = require_enum(); - const validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { - keyword: "type", - schemaType: ["string", "array"] - }, - { - keyword: "nullable", - schemaType: "boolean" - }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const def = { - keyword: "items", - type: "array", - schemaType: [ - "object", - "array", - "boolean" - ], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const items_1 = require_items(); - const def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const additionalItems_1 = require_additionalItems(); - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else min = 1; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ - min, - max - }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); - else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) gen.assign(valid, true); - else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - const def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) gen.if(hasProperty, () => { - for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); - }); - else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: prop - }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const util_1 = require_util(); - const def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) additionalPropertyCode(key); - else gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - else definedProp = codegen_1.nil; - if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const validate_1 = require_validate(); - const code_1 = require_code(); - const util_1 = require_util(); - const additionalProperties_1 = require_additionalProperties(); - const def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) it.definedProperties.add(prop); - if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) applyPropertySchema(prop); - else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const util_2 = require_util(); - const def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) checkMatchingProperties(pat); - if (it.allErrors) validateProperties(pat); - else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); - else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: require_code().validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); - else schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - const schCxt = cxt.subschema({ - keyword: "allOf", - schemaProp: i - }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) gen.if(schValid, validateClause("then")); - else gen.if((0, codegen_1.not)(schValid), validateClause("else")); - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const additionalItems_1 = require_additionalItems(); - const prefixItems_1 = require_prefixItems(); - const items_1 = require_items(); - const items2020_1 = require_items2020(); - const contains_1 = require_contains(); - const dependencies_1 = require_dependencies(); - const propertyNames_1 = require_propertyNames(); - const additionalProperties_1 = require_additionalProperties(); - const properties_1 = require_properties(); - const patternProperties_1 = require_patternProperties(); - const not_1 = require_not(); - const anyOf_1 = require_anyOf(); - const oneOf_1 = require_oneOf(); - const allOf_1 = require_allOf(); - const if_1 = require_if(); - const thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); - else applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self } = it; - if (!opts.validateFormats) return; - if ($data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { - key: schema, - ref: fmtDef, - code - }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ - fmtDef.type || "string", - fmtDef.validate, - (0, codegen_1._)`${fmt}.validate` - ]; - return [ - "string", - fmtDef, - fmt - ]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const format = [require_format$2().default]; - exports.default = format; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError) { - DiscrError["Tag"] = "tag"; - DiscrError["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const types_1 = require_types(); - const compile_1 = require_compile(); - const ref_error_1 = require_ref_error(); - const util_1 = require_util(); - const def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); - const tagName = schema.propertyName; - if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); - if (schema.mapping) throw new Error("discriminator: mapping is not supported"); - if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { - discrError: types_1.DiscrError.Tag, - tag, - tagName - })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { - discrError: types_1.DiscrError.Mapping, - tag, - tagName - }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp - }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; - if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required }) { - return Array.isArray(required) && required.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) addMapping(sch.const, i); - else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); - else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "http://json-schema.org/draft-07/schema#", - "title": "Core schema meta-schema", - "definitions": { - "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$ref": "#" } - }, - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - }, - "type": ["object", "boolean"], - "properties": { - "$id": { - "type": "string", - "format": "uri-reference" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "$ref": { - "type": "string", - "format": "uri-reference" - }, - "$comment": { "type": "string" }, - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "readOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - }, - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, - "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "additionalItems": { "$ref": "#" }, - "items": { - "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], - "default": true - }, - "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, - "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "contains": { "$ref": "#" }, - "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, - "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/definitions/stringArray" }, - "additionalProperties": { "$ref": "#" }, - "definitions": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "properties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependencies": { - "type": "object", - "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } - }, - "propertyNames": { "$ref": "#" }, - "const": true, - "enum": { - "type": "array", - "items": true, - "minItems": 1, - "uniqueItems": true - }, - "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/definitions/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "format": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "if": { "$ref": "#" }, - "then": { "$ref": "#" }, - "else": { "$ref": "#" }, - "allOf": { "$ref": "#/definitions/schemaArray" }, - "anyOf": { "$ref": "#/definitions/schemaArray" }, - "oneOf": { "$ref": "#/definitions/schemaArray" }, - "not": { "$ref": "#" } - }, - "default": true - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const discriminator_1 = require_discriminator(); - const draft7MetaSchema = require_json_schema_draft_07(); - const META_SUPPORT_DATA = ["/properties"]; - const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv = Ajv; - module.exports = exports = Ajv; - module.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js -var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicAnchor = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicAnchor", - schemaType: "string", - code: (cxt) => dynamicAnchor(cxt, cxt.schema) - }; - function dynamicAnchor(cxt, anchor) { - const { gen, it } = cxt; - it.schemaEnv.root.dynamicAnchors[anchor] = true; - const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; - const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); - gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); - } - exports.dynamicAnchor = dynamicAnchor; - function _getValidate(cxt) { - const { schemaEnv, schema, self } = cxt.it; - const { root, baseId, localRefs, meta } = schemaEnv.root; - const { schemaId } = self.opts; - const sch = new compile_1.SchemaEnv({ - schema, - schemaId, - root, - baseId, - localRefs, - meta - }); - compile_1.compileSchema.call(self, sch); - return (0, ref_1.getValidate)(cxt, sch); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js -var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicRef = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicRef", - schemaType: "string", - code: (cxt) => dynamicRef(cxt, cxt.schema) - }; - function dynamicRef(cxt, ref) { - const { gen, keyword, it } = cxt; - if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); - const anchor = ref.slice(1); - if (it.allErrors) _dynamicRef(); - else { - const valid = gen.let("valid", false); - _dynamicRef(valid); - cxt.ok(valid); - } - function _dynamicRef(valid) { - if (it.schemaEnv.root.dynamicAnchors[anchor]) { - const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); - gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); - } else _callRef(it.validateName, valid)(); - } - function _callRef(validate, valid) { - return valid ? () => gen.block(() => { - (0, ref_1.callRef)(cxt, validate); - gen.let(valid, true); - }) : () => (0, ref_1.callRef)(cxt, validate); - } - } - exports.dynamicRef = dynamicRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js -var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const util_1 = require_util(); - const def = { - keyword: "$recursiveAnchor", - schemaType: "boolean", - code(cxt) { - if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); - else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js -var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicRef_1 = require_dynamicRef(); - const def = { - keyword: "$recursiveRef", - schemaType: "string", - code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js -var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const dynamicRef_1 = require_dynamicRef(); - const recursiveAnchor_1 = require_recursiveAnchor(); - const recursiveRef_1 = require_recursiveRef(); - const dynamic = [ - dynamicAnchor_1.default, - dynamicRef_1.default, - recursiveAnchor_1.default, - recursiveRef_1.default - ]; - exports.default = dynamic; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js -var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentRequired", - type: "object", - schemaType: "object", - error: dependencies_1.error, - code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js -var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentSchemas", - type: "object", - schemaType: "object", - code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js -var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["maxContains", "minContains"], - type: "array", - schemaType: "number", - code({ keyword, parentSchema, it }) { - if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js -var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependentRequired_1 = require_dependentRequired(); - const dependentSchemas_1 = require_dependentSchemas(); - const limitContains_1 = require_limitContains(); - const next = [ - dependentRequired_1.default, - dependentSchemas_1.default, - limitContains_1.default - ]; - exports.default = next; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js -var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const def = { - keyword: "unevaluatedProperties", - type: "object", - schemaType: ["boolean", "object"], - trackErrors: true, - error: { - message: "must NOT have unevaluated properties", - params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` - }, - code(cxt) { - const { gen, schema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, props } = it; - if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); - else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); - it.props = true; - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function unevaluatedPropCode(key) { - if (schema === false) { - cxt.setParams({ unevaluatedProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (!(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "unevaluatedProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - function unevaluatedDynamic(evaluatedProps, key) { - return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; - } - function unevaluatedStatic(evaluatedProps, key) { - const ps = []; - for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); - return (0, codegen_1.and)(...ps); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js -var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "unevaluatedItems", - type: "array", - schemaType: ["boolean", "object"], - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - const items = it.items || 0; - if (items === true) return; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items }); - cxt.fail((0, codegen_1._)`${len} > ${items}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); - cxt.ok(valid); - } - it.items = true; - function validateItems(valid, from) { - gen.forRange("i", from, len, (i) => { - cxt.subschema({ - keyword: "unevaluatedItems", - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js -var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const unevaluatedProperties_1 = require_unevaluatedProperties(); - const unevaluatedItems_1 = require_unevaluatedItems(); - const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; - exports.default = unevaluated; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json -var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/schema", - "$vocabulary": { - "https://json-schema.org/draft/2019-09/vocab/core": true, - "https://json-schema.org/draft/2019-09/vocab/applicator": true, - "https://json-schema.org/draft/2019-09/vocab/validation": true, - "https://json-schema.org/draft/2019-09/vocab/meta-data": true, - "https://json-schema.org/draft/2019-09/vocab/format": false, - "https://json-schema.org/draft/2019-09/vocab/content": true - }, - "$recursiveAnchor": true, - "title": "Core and Validation specifications meta-schema", - "allOf": [ - { "$ref": "meta/core" }, - { "$ref": "meta/applicator" }, - { "$ref": "meta/validation" }, - { "$ref": "meta/meta-data" }, - { "$ref": "meta/format" }, - { "$ref": "meta/content" } - ], - "type": ["object", "boolean"], - "properties": { - "definitions": { - "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - }, - "dependencies": { - "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", - "type": "object", - "additionalProperties": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "meta/validation#/$defs/stringArray" }] } - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json -var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/applicator", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, - "$recursiveAnchor": true, - "title": "Applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "additionalItems": { "$recursiveRef": "#" }, - "unevaluatedItems": { "$recursiveRef": "#" }, - "items": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "#/$defs/schemaArray" }] }, - "contains": { "$recursiveRef": "#" }, - "additionalProperties": { "$recursiveRef": "#" }, - "unevaluatedProperties": { "$recursiveRef": "#" }, - "properties": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependentSchemas": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" } - }, - "propertyNames": { "$recursiveRef": "#" }, - "if": { "$recursiveRef": "#" }, - "then": { "$recursiveRef": "#" }, - "else": { "$recursiveRef": "#" }, - "allOf": { "$ref": "#/$defs/schemaArray" }, - "anyOf": { "$ref": "#/$defs/schemaArray" }, - "oneOf": { "$ref": "#/$defs/schemaArray" }, - "not": { "$recursiveRef": "#" } - }, - "$defs": { "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$recursiveRef": "#" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json -var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/content", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, - "$recursiveAnchor": true, - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "contentSchema": { "$recursiveRef": "#" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json -var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/core", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, - "$recursiveAnchor": true, - "title": "Core vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "$id": { - "type": "string", - "format": "uri-reference", - "$comment": "Non-empty fragments not allowed.", - "pattern": "^[^#]*#?$" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "$anchor": { - "type": "string", - "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" - }, - "$ref": { - "type": "string", - "format": "uri-reference" - }, - "$recursiveRef": { - "type": "string", - "format": "uri-reference" - }, - "$recursiveAnchor": { - "type": "boolean", - "default": false - }, - "$vocabulary": { - "type": "object", - "propertyNames": { - "type": "string", - "format": "uri" - }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json -var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/format", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, - "$recursiveAnchor": true, - "title": "Format vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json -var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, - "$recursiveAnchor": true, - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json -var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/validation", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, - "$recursiveAnchor": true, - "title": "Validation vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, - "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, - "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, - "minContains": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 1 - }, - "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, - "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/$defs/stringArray" }, - "dependentRequired": { - "type": "object", - "additionalProperties": { "$ref": "#/$defs/stringArray" } - }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] } - }, - "$defs": { - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 0 - }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js -var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema$1(); - const applicator = require_applicator$1(); - const content = require_content$1(); - const core = require_core$1(); - const format = require_format(); - const metadata = require_meta_data$1(); - const validation = require_validation$1(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2019($data) { - [ - metaSchema, - applicator, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2019; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js -var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const discriminator_1 = require_discriminator(); - const json_schema_2019_09_1 = require_json_schema_2019_09(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; - var Ajv2019 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - this.addVocabulary(dynamic_1.default); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - this.addVocabulary(next_1.default); - this.addVocabulary(unevaluated_1.default); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2019_09_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2019 = Ajv2019; - module.exports = exports = Ajv2019; - module.exports.Ajv2019 = Ajv2019; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2019; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js -var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft2020Vocabularies = [ - dynamic_1.default, - core_1.default, - validation_1.default, - (0, applicator_1.default)(true), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary, - next_1.default, - unevaluated_1.default - ]; - exports.default = draft2020Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json -var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/schema", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/core": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true, - "https://json-schema.org/draft/2020-12/vocab/meta-data": true, - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$dynamicAnchor": "meta", - "title": "Core and Validation specifications meta-schema", - "allOf": [ - { "$ref": "meta/core" }, - { "$ref": "meta/applicator" }, - { "$ref": "meta/unevaluated" }, - { "$ref": "meta/validation" }, - { "$ref": "meta/meta-data" }, - { "$ref": "meta/format-annotation" }, - { "$ref": "meta/content" } - ], - "type": ["object", "boolean"], - "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", - "properties": { - "definitions": { - "$comment": "\"definitions\" has been replaced by \"$defs\".", - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "deprecated": true, - "default": {} - }, - "dependencies": { - "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", - "type": "object", - "additionalProperties": { "anyOf": [{ "$dynamicRef": "#meta" }, { "$ref": "meta/validation#/$defs/stringArray" }] }, - "deprecated": true, - "default": {} - }, - "$recursiveAnchor": { - "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", - "$ref": "meta/core#/$defs/anchorString", - "deprecated": true - }, - "$recursiveRef": { - "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", - "$ref": "meta/core#/$defs/uriReferenceString", - "deprecated": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json -var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/applicator", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, - "$dynamicAnchor": "meta", - "title": "Applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "prefixItems": { "$ref": "#/$defs/schemaArray" }, - "items": { "$dynamicRef": "#meta" }, - "contains": { "$dynamicRef": "#meta" }, - "additionalProperties": { "$dynamicRef": "#meta" }, - "properties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependentSchemas": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "propertyNames": { "$dynamicRef": "#meta" }, - "if": { "$dynamicRef": "#meta" }, - "then": { "$dynamicRef": "#meta" }, - "else": { "$dynamicRef": "#meta" }, - "allOf": { "$ref": "#/$defs/schemaArray" }, - "anyOf": { "$ref": "#/$defs/schemaArray" }, - "oneOf": { "$ref": "#/$defs/schemaArray" }, - "not": { "$dynamicRef": "#meta" } - }, - "$defs": { "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$dynamicRef": "#meta" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json -var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, - "$dynamicAnchor": "meta", - "title": "Unevaluated applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "unevaluatedItems": { "$dynamicRef": "#meta" }, - "unevaluatedProperties": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json -var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/content", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, - "$dynamicAnchor": "meta", - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentEncoding": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentSchema": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json -var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/core", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, - "$dynamicAnchor": "meta", - "title": "Core vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "$id": { - "$ref": "#/$defs/uriReferenceString", - "$comment": "Non-empty fragments not allowed.", - "pattern": "^[^#]*#?$" - }, - "$schema": { "$ref": "#/$defs/uriString" }, - "$ref": { "$ref": "#/$defs/uriReferenceString" }, - "$anchor": { "$ref": "#/$defs/anchorString" }, - "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, - "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, - "$vocabulary": { - "type": "object", - "propertyNames": { "$ref": "#/$defs/uriString" }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" } - } - }, - "$defs": { - "anchorString": { - "type": "string", - "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" - }, - "uriString": { - "type": "string", - "format": "uri" - }, - "uriReferenceString": { - "type": "string", - "format": "uri-reference" - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json -var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, - "$dynamicAnchor": "meta", - "title": "Format vocabulary meta-schema for annotation results", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json -var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, - "$dynamicAnchor": "meta", - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json -var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/validation", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, - "$dynamicAnchor": "meta", - "title": "Validation vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, - "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, - "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, - "minContains": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 1 - }, - "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, - "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/$defs/stringArray" }, - "dependentRequired": { - "type": "object", - "additionalProperties": { "$ref": "#/$defs/stringArray" } - } - }, - "$defs": { - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 0 - }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js -var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema(); - const applicator = require_applicator(); - const unevaluated = require_unevaluated(); - const content = require_content(); - const core = require_core(); - const format = require_format_annotation(); - const metadata = require_meta_data(); - const validation = require_validation(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2020($data) { - [ - metaSchema, - applicator, - unevaluated, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2020; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js -var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; - const core_1 = require_core$3(); - const draft2020_1 = require_draft2020(); - const discriminator_1 = require_discriminator(); - const json_schema_2020_12_1 = require_json_schema_2020_12(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; - var Ajv2020 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - draft2020_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2020_12_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2020 = Ajv2020; - module.exports = exports = Ajv2020; - module.exports.Ajv2020 = Ajv2020; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2020; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { - validate, - compare - }; - } - exports.fullFormats = { - date: fmtDef(date, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, - "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, - "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, - "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, - byte, - int32: { - type: "number", - validate: validateInt32 - }, - int64: { - type: "number", - validate: validateInt64 - }, - float: { - type: "number", - validate: validateNumber - }, - double: { - type: "number", - validate: validateNumber - }, - password: true, - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - const DAYS = [ - 0, - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - ]; - function date(str) { - const matches = DATE.exec(str); - if (!matches) return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) return void 0; - if (d1 > d2) return 1; - if (d1 < d2) return -1; - return 0; - } - const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time(str) { - const matches = TIME.exec(str); - if (!matches) return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; - if (hr <= 23 && min <= 59 && sec < 60) return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) return void 0; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) return void 0; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) return 1; - if (t1 < t2) return -1; - return 0; - } - const DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) return void 0; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) return void 0; - return res || compareTime(t1, t2); - } - const NOT_URI_FRAGMENT = /\/|:/; - const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - const MIN_INT32 = -(2 ** 31); - const MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - const Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - const ajv_1 = require_ajv(); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - formatMaximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - formatMinimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - formatExclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - formatExclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self } = it; - if (!opts.validateFormats) return; - const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); - if (fCxt.$data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self.formats[format]; - if (!fmtDef || fmtDef === true) return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - const formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const formats_1 = require_formats(); - const limit_1 = require_limit(); - const codegen_1 = require_codegen(); - const fullName = new codegen_1.Name("fullFormats"); - const fastName = new codegen_1.Name("fastFormats"); - const formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); - if (opts.keywords) (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; - if (!f) throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) ajv.addFormat(f, fs[f]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; -})); - -//#endregion -//#region ../core-internal/src/validators/ajvProvider.ts -var import_ajv = require_ajv(); -var import__2019 = require__2019(); -var import__2020 = require__2020(); -var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); -/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ -const ajvProvider_CEoC_sr_addFormats = import_dist.default; -function createDefaultAjvInstance(engineClass) { - const ajv = new engineClass({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - ajvProvider_CEoC_sr_addFormats(ajv); - return ajv; -} -/** -* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` -* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). -* -* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` -* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class -* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv -* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching -* v1's default engine), while the cfworker provider ignores them per spec. -* Schemas declaring any other `$schema` are -* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate -* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type -* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 -* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and -* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would -* silently downgrade dialect. -* -* @example Use with default configuration -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" -* const validator = new AjvJsonSchemaValidator(); -* ``` -* -* @example Use with a custom AJV instance -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -* -* @example Register ajv-formats -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -*/ -var AjvJsonSchemaValidator = class { - _ajv; - /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ - _ajvDraft7; - /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ - _ajv2019; - /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ - _userAjv; - /** - * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is - * used for **every** schema regardless of its declared `$schema` (the caller owns dialect - * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, - * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with - * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so - * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never - * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter - * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. - */ - constructor(ajv) { - this._userAjv = ajv !== void 0; - this._ajv = ajv; - } - /** The underlying 2020-12 engine — the default instance is created on first use. */ - get ajv() { - return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); - } - /** - * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for - * every schema — do not second-guess by `$schema` (bring-your-own-validator means - * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → - * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. - */ - _engineFor(schema) { - if (this._userAjv) return this.ajv; - const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); - if (dialect === "2020-12") return this.ajv; - if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); - return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); - } - getValidator(schema) { - const engine = this._engineFor(schema); - const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); - return (input) => { - return ajvValidator(input) ? { - valid: true, - data: input, - errorMessage: void 0 - } : { - valid: false, - data: void 0, - errorMessage: engine.errorsText(ajvValidator.errors) - }; - }; - } -}; -/** -* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. -* The full v1-equivalent construction is: -* -* ```ts -* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* new AjvJsonSchemaValidator(ajv); -* ``` -* -* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque -* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` -* validation that the v1 default had). -* -* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream -* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own -* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. -*/ -const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; - -//#endregion - -//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map - - - - - - - - -//#region src/server/completable.ts -const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); -/** -* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. -* -* @example -* ```ts source="./completable.examples.ts#completable_basicUsage" -* server.registerPrompt( -* 'review-code', -* { -* title: 'Code Review', -* argsSchema: z.object({ -* language: completable(z.string().describe('Programming language'), value => -* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) -* ) -* }) -* }, -* ({ language }) => ({ -* messages: [ -* { -* role: 'user' as const, -* content: { -* type: 'text' as const, -* text: `Review this ${language} code.` -* } -* } -* ] -* }) -* ); -* ``` -* -* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions -*/ -function completable(schema, complete) { - Object.defineProperty(schema, COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** -* Checks if a schema is completable (has completion metadata). -*/ -function isCompletable(schema) { - return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; -} -/** -* Gets the completer callback from a completable schema, if it exists. -*/ -function getCompleter(schema) { - return schema[COMPLETABLE_SYMBOL]?.complete; -} - -//#endregion -//#region src/server/sseKeepAlive.ts -/** Default interval between SSE keep-alive comment frames. */ -const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; -const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); -/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ -function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { - if (!Number.isFinite(intervalMs) || intervalMs < 1) return; - const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); - timer.unref?.(); - return timer; -} - -//#endregion -//#region src/server/serverEventBus.ts -/** -* A `ServerEventBus` backed by an in-process listener set. -* -* `publish()` delivers synchronously to the live listener set (a listener -* unsubscribing itself mid-dispatch is safe; the entry's listen-router -* listeners never unsubscribe peers). A throwing listener does not stop -* delivery to the others. -*/ -var mcp_DXXb3Vv3_InMemoryServerEventBus = class { - _listeners = /* @__PURE__ */ new Set(); - /** - * @param onerror - Optional callback for errors thrown by listeners - * during dispatch. - */ - constructor(onerror) { - this.onerror = onerror; - } - publish(event) { - for (const listener of this._listeners) try { - listener(event); - } catch (error) { - this.onerror?.(error instanceof Error ? error : new Error(String(error))); - } - } - subscribe(listener) { - this._listeners.add(listener); - let live = true; - return () => { - if (!live) return; - live = false; - this._listeners.delete(listener); - }; - } - /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ - get listenerCount() { - return this._listeners.size; - } -}; -/** Build a {@linkcode ServerNotifier} over a bus. */ -function mcp_DXXb3Vv3_createServerNotifier(bus) { - return { - toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), - promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), - resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), - resourceUpdated: (uri) => bus.publish({ - kind: "resource_updated", - uri - }) - }; -} -/** -* Whether a `subscriptions/listen` filter accepts a given change event. -* -* Pure: no I/O, no mutation. The filter governs ONLY the four -* subscription-gated change types — non-gated notifications never reach the -* bus and are not modeled here. -* -* `resource_updated` matches only when `resourceSubscriptions` is present and -* contains the event's URI exactly (per the spec: "for these resource URIs"). -*/ -function listenFilterAccepts(filter, event) { - switch (event.kind) { - case "tools_list_changed": return filter.toolsListChanged === true; - case "prompts_list_changed": return filter.promptsListChanged === true; - case "resources_list_changed": return filter.resourcesListChanged === true; - case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); - } -} -/** -* The honored subset of a requested filter: keeps only the fields the client -* explicitly opted in to (drops `false` and absent fields), narrowed against -* the server's declared capabilities when supplied. The serving entry sends -* this back in `notifications/subscriptions/acknowledged` so the ack reflects -* what the server can actually deliver. -* -* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` -* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. -* - `resourceSubscriptions` is honored only when -* `capabilities.resources.subscribe` is advertised. -* -* `capabilities` is optional on this pure helper for test convenience only — -* both wired routers REQUIRE capabilities at the call site (the HTTP router's -* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws -* before `setServerCapabilities()` was called), so the fail-open -* `undefined → honor everything` branch is never reachable on a wired entry. -*/ -function honoredSubset(requested, capabilities) { - const honored = {}; - const allow = (bit) => capabilities === void 0 || bit === true; - if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; - if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; - if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; - if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; - return honored; -} -/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ -function serverEventToNotification(event) { - switch (event.kind) { - case "tools_list_changed": return { method: "notifications/tools/list_changed" }; - case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; - case "resources_list_changed": return { method: "notifications/resources/list_changed" }; - case "resource_updated": return { - method: "notifications/resources/updated", - params: { uri: event.uri } - }; - } -} - -//#endregion -//#region src/server/listenRouter.ts -/** Default capacity guard: refuse a new subscription when this many are already open. */ -const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; -function jsonRpcError(id, code, message) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message - }, - id - }, { status: 200 }); -} -/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ -function stampSubscriptionId(notification, subscriptionId) { - return { - method: notification.method, - params: { - ...notification.params, - _meta: { - ...notification.params?._meta, - [SUBSCRIPTION_ID_META_KEY]: subscriptionId - } - } - }; -} -/** -* Read the requested filter off a `subscriptions/listen` request body. -* Returns the validated filter, or `undefined` when `params.notifications` -* is absent or fails the schema (the caller answers `-32602` — the spec -* marks `notifications` REQUIRED on the listen request). -*/ -function parseListenFilter(message) { - const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); - return outcome.ok ? outcome.value.params?.notifications : void 0; -} -function mcp_DXXb3Vv3_createListenRouter(options) { - const { bus, onerror } = options; - const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; - const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; - const open = /* @__PURE__ */ new Set(); - function serve(message, signal, capabilities, serverInfo) { - if (open.size >= maxSubscriptions) { - onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); - return jsonRpcError(message.id, -32603, "Subscription limit reached"); - } - const filter = parseListenFilter(message); - if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); - const honored = honoredSubset(filter, capabilities); - const subscriptionId = message.id; - const encoder = new TextEncoder(); - let controller; - let closed = false; - let unsubscribe; - let keepAliveTimer; - let abortCleanup; - const writeFrame = (frame) => { - if (closed) return; - try { - controller.enqueue(encoder.encode(frame)); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - }; - const writeNotification = (method, params) => { - writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - method, - params - })}\n\n`); - }; - const teardown = (graceful) => { - if (closed) return; - if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - id: subscriptionId, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: subscriptionId, - [SERVER_INFO_META_KEY]: serverInfo - } - } - })}\n\n`); - closed = true; - try { - unsubscribe?.(); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - abortCleanup?.(); - open.delete(teardown); - try { - controller.close(); - } catch {} - }; - const readable = new ReadableStream({ - start(streamController) { - controller = streamController; - const ack = stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, subscriptionId); - writeNotification(ack.method, ack.params); - unsubscribe = bus.subscribe((event) => { - if (closed || !listenFilterAccepts(honored, event)) return; - const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); - writeNotification(note.method, note.params); - }); - keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); - open.add(teardown); - }, - cancel() { - teardown(false); - } - }); - if (signal !== void 0) if (signal.aborted) teardown(false); - else { - const onAbort = () => teardown(false); - signal.addEventListener("abort", onAbort, { once: true }); - abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - return new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - }); - } - return { - serve, - closeAll() { - for (const teardown of open) teardown(true); - }, - get openCount() { - return open.size; - } - }; -} -const CHANGE_NOTIFICATION_METHODS = new Set([ - "notifications/tools/list_changed", - "notifications/prompts/list_changed", - "notifications/resources/list_changed", - "notifications/resources/updated" -]); -/** -* Per-connection listen state for the stdio entry. One instance is held by -* `serveStdio` for the connection lifetime; it routes inbound -* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound -* change notifications onto the active subscriptions. No bus — the long-lived -* pinned instance's existing `send*ListChanged()` calls feed straight into -* `routeOutbound()`. -*/ -var mcp_DXXb3Vv3_StdioListenRouter = class { - /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ - _subs = /* @__PURE__ */ new Map(); - /** - * The serving instance's declared capabilities. Filled in by the entry - * once the modern instance is constructed (the router is created before - * the instance exists), so the acknowledged filter is narrowed against - * what the server can actually deliver. - */ - _serverCapabilities; - /** - * The serving instance's identity, stamped onto the graceful-close - * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends - * `ResultMetaObject`). Handed over together with the capabilities. - */ - _serverInfo; - constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { - this._maxSubscriptions = _maxSubscriptions; - this._serverCapabilities = serverCapabilities; - this._serverInfo = serverInfo; - } - /** - * Record the serving instance's declared capabilities and identity once - * it has been constructed. Called by `serveStdio`'s connect path; - * subsequent `serve()` calls narrow the honored filter against the - * capabilities, and `teardownAll()` stamps the identity. - */ - setServerCapabilities(capabilities, serverInfo) { - this._serverCapabilities = capabilities; - if (serverInfo !== void 0) this._serverInfo = serverInfo; - } - /** Whether `id` is an active listen subscription on this connection. */ - has(id) { - return this._subs.has(id); - } - /** - * Serve one inbound `subscriptions/listen` request: registers the - * subscription and returns the stamped acknowledged notification (or, on - * capacity / params rejection, the in-band JSON-RPC error response). - * - * @throws when called before {@linkcode setServerCapabilities} (or the - * constructor) has supplied the serving instance's capabilities. Honoring a - * filter without knowing the server's advertised capabilities would fail - * open (deliver unadvertised types); the entry guarantees capabilities are - * set before any listen request is routed here. - */ - serve(message) { - if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); - if (this._subs.size >= this._maxSubscriptions) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32603, - message: "Subscription limit reached" - } - }; - const filter = parseListenFilter(message); - if (filter === void 0) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" - } - }; - const honored = honoredSubset(filter, this._serverCapabilities); - this._subs.set(message.id, honored); - return stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, message.id); - } - /** - * Tear down one subscription (inbound `notifications/cancelled`). Returns - * `true` when a subscription was removed. After this call NOTHING further - * is delivered for that subscription id (the post-cancel hardening). - */ - cancel(id) { - return this._subs.delete(id); - } - /** - * Route an outbound notification through the active subscriptions. - * - * - For a subscription-gated change notification, returns one stamped copy - * per subscription that opted in to it (an empty array means it is - * dropped — the modern era never delivers an un-requested change type). - * - For any other outbound message, returns `'passthrough'` (the entry - * forwards it as-is). - */ - routeOutbound(message) { - if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; - const uriParam = message.params?.["uri"]; - const uri = typeof uriParam === "string" ? uriParam : void 0; - const event = notificationToServerEvent(message.method, uri); - const out = []; - for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ - method: message.method, - params: message.params ?? {} - }, subscriptionId)); - return out; - } - /** - * Server-side graceful teardown of every active subscription: returns the - * empty `subscriptions/listen` JSON-RPC result for each subscription id — - * the spec's graceful-close signal, `_meta` carrying the subscription id - * and the serving instance's identity — for the entry to emit before - * closing the wire. Clears the set so nothing further is delivered. - */ - teardownAll() { - const out = []; - for (const id of this._subs.keys()) out.push({ - jsonrpc: "2.0", - id, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: id, - ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } - } - } - }); - this._subs.clear(); - return out; - } -}; -function notificationToServerEvent(method, uri) { - switch (method) { - case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; - case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; - case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; - default: return { - kind: "resource_updated", - uri: uri ?? "" - }; - } -} - -//#endregion -//#region src/server/legacyInputRequiredShim.ts -/** -* Default handler re-entries per originating request — tighter than the -* client driver's 10 because the shim holds a live wire request open. -*/ -const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; -/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ -const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; -/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ -function resolveLegacyShimOptions(options) { - if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); - if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); - return { - maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, - roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, - legacyShim: options?.legacyShim ?? true - }; -} -/** -* Validates one `inputRequests` entry: malformed or unknown kinds are server -* bugs and fail loudly on both eras. Shared by the modern seam's capability -* check and the shim's gate. -*/ -function coerceEmbeddedInputRequest(method, key, entry) { - if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); - const embedded = entry; - const required = requiredClientCapabilitiesForInputRequest(embedded); - if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); - return { - embedded, - required - }; -} -/** -* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 -* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a -* getRandomValues fallback for runtimes without `randomUUID`). -*/ -function syntheticElicitationId() { - const webCrypto = globalThis.crypto; - if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); - const bytes = new Uint8Array(16); - webCrypto.getRandomValues(bytes); - bytes[6] = bytes[6] & 15 | 64; - bytes[8] = bytes[8] & 63 | 128; - const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} -/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ -function legacyShimFailure(method, message) { - if (method === "tools/call") return { - content: [{ - type: "text", - text: message - }], - isError: true - }; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); -} -/** The fulfilment loop — see the module doc for the contract. */ -var LegacyInputRequiredShim = class { - constructor(_host) { - this._host = _host; - } - async fulfill(method, handler, request, ctx, firstResult) { - const { maxRounds, roundTimeoutMs } = this._host; - const outerSignal = ctx.mcpReq.signal; - let current = firstResult; - let round = 0; - while (true) { - round += 1; - if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); - const inputRequests = current.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const requestState = typeof current.requestState === "string" ? current.requestState : void 0; - if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - let responses; - if (hasInputRequests) { - const declared = this._host.resolvedClientCapabilities(ctx); - const coerced = []; - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); - if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); - coerced.push([key, embedded]); - } - const roundAbort = linkedRoundAbort(outerSignal); - try { - const legOptions = { - relatedRequestId: ctx.mcpReq.id, - timeout: roundTimeoutMs, - resetTimeoutOnProgress: true, - onprogress: () => {}, - signal: roundAbort.signal - }; - const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { - try { - return [key, await this._dispatchLeg(embedded, legOptions)]; - } catch (error) { - roundAbort.abort(error); - throw error; - } - })); - responses = Object.fromEntries(fulfilled); - } catch (error) { - if (outerSignal.aborted) throw error; - return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); - } finally { - roundAbort.dispose(); - } - } else await sleep((/* inlined export .C */250), outerSignal); - let ctxNext = { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - inputResponses: responses, - droppedInputResponseKeys: void 0, - requestState: requestStateAccessor(requestState) - } - }; - if (requestState !== void 0) { - const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); - if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); - } - const next = await handler(request, ctxNext); - if (!isInputRequiredResult(next)) return next; - current = next; - } - } - /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ - async _dispatchLeg(embedded, options) { - switch (embedded.method) { - case "elicitation/create": { - let params = embedded.params; - if (params.mode === "url" && params.elicitationId === void 0) params = { - ...params, - elicitationId: syntheticElicitationId() - }; - return await this._host.sendElicitation(params, options); - } - case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); - case "roots/list": return await this._host.listRoots(embedded.params, options); - } - } -}; - -//#endregion -//#region src/server/server.ts -/** -* The request methods whose 2026-07-28 result vocabulary includes -* `input_required` (the multi round-trip methods). Returning an -* input-required result from any other handler is a server bug. -*/ -const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ - "tools/call", - "prompts/get", - "resources/read" -]); -let writeClientIdentity; -let installDiscoverHandler; -let readServerIdentity; -/** -* Package-internal: backfills the connection-scoped client-identity fields of a -* per-request server instance from the request's validated `_meta` envelope, so the -* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} -* accessors keep answering on instances that never see an `initialize` handshake. -* Not public API. -*/ -function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { - writeClientIdentity(server, identity); -} -/** -* Package-internal: installs the modern-only `server/discover` handler on an instance -* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern -* revisions the entry serves appear in the instance's supported-versions list (so the -* discover advertisement and version-mismatch errors name them). Idempotent. -* Hand-constructed instances are unaffected: nothing else calls this, so they keep -* answering `-32601` unless their own supported-versions list opts into a modern -* revision. Not public API. -*/ -function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { - installDiscoverHandler(server, servedModernVersions); -} -/** -* Package-internal: the instance's implementation identity, for the serving -* entries to stamp onto entry-built results (the `subscriptions/listen` -* graceful-close result — built outside the encode seam, but the spec's -* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries -* the serverInfo SHOULD like every other result). Not public API. -*/ -function mcp_DXXb3Vv3_serverIdentityOf(server) { - return readServerIdentity(server); -} -/** -* An MCP server on top of a pluggable transport. -* -* This server will automatically respond to the initialization flow as initiated from the client. -* -* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. -*/ -var Server = class extends Protocol { - _clientCapabilities; - _clientVersion; - static { - writeClientIdentity = (server, identity) => { - if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; - if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; - }; - installDiscoverHandler = (server, servedModernVersions) => { - const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); - if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; - server.setRequestHandler("server/discover", () => server._ondiscover()); - }; - readServerIdentity = (server) => server._serverInfo; - } - _capabilities; - _instructions; - _jsonSchemaValidator; - _cacheHints; - _requestStateVerify; - _inputRequiredServing; - _legacyShim; - /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ - _legacyInputRequiredShim() { - return this._legacyShim ??= new LegacyInputRequiredShim({ - maxRounds: this._inputRequiredServing.maxRounds, - roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, - resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), - verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), - sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), - sendSampling: (params, options) => this.createMessage(params, options), - listRoots: (params, options) => this.listRoots(params, options) - }); - } - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). - */ - oninitialized; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this._requestStateVerify = options?.requestState?.verify; - this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); - if (options?.cacheHints !== void 0) { - for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); - this._cacheHints = options.cacheHints; - } - this.setRequestHandler("initialize", (request) => this._oninitialize(request)); - this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); - if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); - if (this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Registers the built-in `logging/setLevel` request handler. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - _registerLoggingHandler() { - this.setRequestHandler("logging/setLevel", async (request, ctx) => { - const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; - const { level } = request.params; - const parseResult = parseSchema(LoggingLevelSchema, level); - if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); - return {}; - }); - } - buildContext(ctx, transportInfo) { - const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - log: (level, data, logger) => { - if (!this._capabilities.logging) return Promise.resolve(); - let threshold; - if (this._servedModernEra()) { - threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; - if (threshold === void 0) return Promise.resolve(); - } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); - if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); - return ctx.mcpReq.notify({ - method: "notifications/message", - params: { - level, - data, - logger - } - }); - }, - elicitInput: (params, options) => this.elicitInput(params, options), - requestSampling: (params, options) => this.createMessage(params, options) - }, - http: hasHttpInfo ? { - ...ctx.http, - req: transportInfo?.request, - closeSSE: transportInfo?.closeSSEStream, - closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream - } : void 0 - }; - } - _loggingLevels = /* @__PURE__ */ new Map(); - LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); - const hadLogging = !!this._capabilities.logging; - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Enforces server-side validation for `tools/call` results regardless of how the - * handler was registered, attaches the configured per-operation cache hint - * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` - * for results that do not provide their own, and owns the multi-round-trip - * seam: on the methods whose 2026-07-28 result vocabulary includes - * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an - * input-required return skips result-schema validation and is checked - * against the served era, the at-least-one rule, and the request's own - * declared client capabilities; on every other method an input-required - * return is a server bug and fails loudly. The hint rides a symbol-keyed - * property that is never serialized, so 2025-era responses are unaffected. - */ - _wrapHandler(method, handler) { - if (method !== "tools/call") { - const cacheHint = this._cacheHints?.[method]; - const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); - if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { - const result = await handler(request, ctx); - if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - }; - return async (request, ctx) => { - const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); - if (isInputRequiredResult(result)) { - if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - } - return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); - }; - } - return async (request, ctx) => { - const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - const validatedRequest = codec.validateRequest("tools/call", request); - if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); - const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); - if (isInputRequiredResult(result)) return result; - const normalizedResult = normalizeContentlessToolResult(result); - const validationResult = codec.validateResult("tools/call", normalizedResult); - if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); - return validationResult.value; - }; - } - /** - * Whether this instance is bound to a 2026-07-28-or-later protocol - * revision. Era is instance state — a serving entry (`createMcpHandler`, - * `serveStdio`) marks the instance modern at construction; a 2025-era - * `initialize` handshake binds it legacy. The multi-round-trip seam reads - * this directly: there is no per-request era consult. - */ - _servedModernEra() { - return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); - } - /** - * Invokes a handler for one of the multi-round-trip methods and applies - * the input-required seam: - * - * - a `UrlElicitationRequiredError` (or any 2025-style server→client - * request idiom) escaping the handler on a request served on the - * 2026-07-28 era fails LOUDLY with a clear steer to - * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the - * 2026-07-28 wire and the throw is not silently converted. Requests - * served on the 2025 era keep today's `-32042` behavior byte-exact (the - * error is rethrown unchanged). - * - an input-required RETURN toward a 2026-07-28 request must satisfy - * the at-least-one rule, and every embedded request must be covered by - * the capabilities declared on the request's envelope (violations - * answer the typed `-32021` error). Toward a 2025-era request the - * return is fulfilled by the default-on legacy shim, whose own gate - * consults the initialize-declared capabilities and surfaces - * violations per family; `inputRequired.legacyShim: false` restores - * the pre-shim loud failure. - */ - async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { - const servedModern = this._servedModernEra(); - const rawRequestState = ctx.mcpReq.requestState(); - if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - let ctxForHandler = ctx; - if (typeof rawRequestState === "string") { - const decoded = await this._verifyRequestState(rawRequestState, ctx, method); - if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); - } - let result; - try { - result = await handler(request, ctxForHandler); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { - if (!servedModern) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); - } - throw error; - } - if (!isInputRequiredResult(result)) return result; - if (!servedModern) { - if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); - return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); - } - const inputRequests = result.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const hasRequestState = typeof result.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - if (hasInputRequests) { - const declared = this._inputRequestCapabilityView(ctx); - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); - if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); - } - } - return result; - } - /** - * Runs the configured `requestState.verify` hook and returns its - * resolved value (`undefined` when unconfigured or the hook returns - * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; - * the reason goes to `onerror` only. - */ - async _verifyRequestState(state, ctx, method) { - if (this._requestStateVerify === void 0) return; - try { - return await this._requestStateVerify(state, ctx); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - } - } - /** - * The per-request resolved client-capabilities view: the request's own - * `_meta` envelope on the 2026 era; the `initialize`-declared state on a - * 2025-era connection. Per-request instances that never saw an - * initialize (stateless legacy) hold nothing, so gates refuse there. - */ - _inputRequestCapabilityView(ctx) { - return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; - } - /** - * Guard for the push-style server→client request APIs ({@linkcode createMessage}, - * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a - * modern-era instance: the 2026-07-28 revision has no server→client request - * channel, so the call fails before any wire traffic with a typed error - * whose message steers to `inputRequired(...)`. The base era gate would - * also reject it; this guard runs first to carry the steer. - */ - _assertPushApiInServedEra(method) { - if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { - method, - era: "2026-07-28" - }); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); - break; - case "roots/list": - if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); - break; - case "ping": break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); - break; - case "notifications/cancelled": break; - case "notifications/progress": break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); - break; - case "logging/setLevel": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); - break; - case "ping": - case "initialize": break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); - const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; - this._negotiatedProtocolVersion = protocolVersion; - this.transport?.setProtocolVersion?.(protocolVersion); - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` - * lists only modern revisions (2025-era versions are negotiated via `initialize`); - * the capabilities are advertised as-is, listChanged/subscribe bits included - * (see {@linkcode discoverAdvertisedCapabilities}). - */ - _ondiscover() { - return { - supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), - capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * The identity the 2026-era encode seam stamps into every outbound - * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR - * #3002: servers SHOULD identify themselves on every response). - */ - _outboundServerInfo() { - return this._serverInfo; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * declared capabilities, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * name and version, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientVersion() { - return this._clientVersion; - } - /** - * After initialization has completed, this will be populated with the protocol version negotiated - * with the client (the version the server responded with during the initialize handshake), or - * `undefined` before initialization. - * - * @deprecated Read the protocol revision from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the - * request was sent for, while on 2025-era connections this accessor keeps returning the - * `initialize`-negotiated version. The accessor remains functional — instances serving the - * 2026-07-28 era report that revision. - */ - getNegotiatedProtocolVersion() { - return this._negotiatedProtocolVersion; - } - /** - * Project a `tools/call` result through this instance's negotiated wire - * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on - * the 2025 era the `{result:…}` wrap when `structuredContent` is a - * non-object value or the advertised `outputSchema` had a non-object root. - * Identity for object-shaped `structuredContent` on the 2026 era. - * - * `McpServer`'s built-in `tools/call` handler routes through this method. - * Low-level `setRequestHandler('tools/call', …)` authors call it - * themselves so the projection lives in one place (the codec) and the - * server-side handler stays era-blind. - * - * This is the only codec function exposed on `Server` — the full - * `WireCodec` is intentionally not part of the public surface. - */ - projectCallToolResult(result, advertisedOutputSchema) { - return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); - } - /** - * Returns the current server capabilities. - */ - getCapabilities() { - return this._capabilities; - } - /** - * Sends a `ping` request to the connected client. - * - * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. - * If your factory serves both eras, this only works on the legacy path. - */ - async ping() { - this._assertPushApiInServedEra("ping"); - return this.request({ method: "ping" }); - } - async createMessage(params, options) { - this._assertPushApiInServedEra("sampling/createMessage"); - if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); - if (params.messages.length > 0) { - const lastMessage = params.messages.at(-1); - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); - if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - const hasTools = Boolean(params.tools || params.toolChoice); - const wide = await this.request({ - method: "sampling/createMessage", - params - }, options); - const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); - if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); - return outcome.value; - } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - * - * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) - * instead. The 2025 push-style server-to-client request model is replaced by input_required - * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the - * legacy path. - */ - async elicitInput(params, options) { - this._assertPushApiInServedEra("elicitation/create"); - switch (params.mode ?? "form") { - case "url": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); - break; - case "form": - if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); - break; - } - return this._sendElicitationLeg(params, options); - } - /** - * The capability-check-free core of {@linkcode elicitInput}. The shim - * uses it because its gate differs from the public checks: a bare - * `elicitation: {}` counts as form support (the pre-mode rule), and - * accepted content passes through unvalidated for parity with the - * modern client driver (handlers validate via the schema-aware - * `acceptedContent` overload and can re-ask). - */ - async _sendElicitationLeg(params, options, behavior) { - const mode = params.mode ?? "form"; - const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; - switch (mode) { - case "url": { - const urlParams = params; - return this.request({ - method: "elicitation/create", - params: urlParams - }, options); - } - case "form": { - const formParams = params.mode === "form" ? params : { - ...params, - mode: "form" - }; - const result = await this.request({ - method: "elicitation/create", - params: formParams - }, options); - if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { - const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); - if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * The notification (and the `elicitationId` it references) exists only on protocol revision - * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the - * returned callback rejects with a typed local error before anything reaches the transport - * (the method is not part of that revision's wire registry). - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { elicitationId } - }, options); - } - /** - * Requests the list of roots from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, - * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 - * push-style server-to-client request model is replaced by input_required results in the - * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. - */ - async listRoots(params, options) { - this._assertPushApiInServedEra("roots/list"); - return this.request({ - method: "roots/list", - params - }, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ - method: "notifications/message", - params - }); - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - async sendResourceListChanged() { - return this.notification({ method: "notifications/resources/list_changed" }); - } - async sendToolListChanged() { - return this.notification({ method: "notifications/tools/list_changed" }); - } - async sendPromptListChanged() { - return this.notification({ method: "notifications/prompts/list_changed" }); - } -}; -/** -* The capability set a server advertises on `server/discover`. Pure — never -* mutates the input; the legacy `initialize` advertisement is untouched. -* -* The serving entries serve `subscriptions/listen` themselves, so the -* `listChanged` and `resources.subscribe` capability bits are advertised -* as-is: a modern-era client uses them to decide which notification types to -* request on its listen filter. -*/ -function discoverAdvertisedCapabilities(capabilities) { - return { ...capabilities }; -} - -//#endregion -//#region src/server/mcp.ts -/** -* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. -* For advanced usage (like sending notifications or setting custom request handlers), use the underlying -* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. -* -* @example -* ```ts source="./mcp.examples.ts#McpServer_basicUsage" -* const server = new McpServer({ -* name: 'my-server', -* version: '1.0.0' -* }); -* ``` -*/ -var mcp_DXXb3Vv3_McpServer = class { - /** - * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. - */ - server; - _registeredResources = {}; - _registeredResourceTemplates = {}; - _registeredTools = {}; - _registeredPrompts = {}; - /** - * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 - * registration-time scan and the pre-dispatch validation step share one - * conversion instead of paying it twice per request under the - * per-request-factory `createMcpHandler` model. - */ - _toolInputSchemaJson = {}; - /** - * The JSON-serialized `inputSchema` of a registered tool, or `undefined` - * when no such tool is registered. Used by the HTTP entry's pre-dispatch - * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema - * `tools/list` would emit, before dispatch reaches the handler). - * - * @internal - */ - toolInputSchemaJson(name) { - const tool = this._registeredTools[name]; - if (tool === void 0 || !tool.enabled) return void 0; - if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; - if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; - try { - const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - return json; - } catch { - return; - } - } - constructor(serverInfo, options) { - this.server = new Server(serverInfo, options); - if (options?.capabilities?.tools) this.setToolRequestHandlers(); - if (options?.capabilities?.resources) this.setResourceRequestHandlers(); - if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" - * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); - * const transport = new StdioServerTransport(); - * await server.connect(transport); - * ``` - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - _toolHandlersInitialized = false; - setToolRequestHandlers() { - if (this._toolHandlersInitialized) return; - this.server.assertCanSetRequestHandler("tools/list"); - this.server.assertCanSetRequestHandler("tools/call"); - this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); - this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations, - icons: tool.icons, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); - return toolDefinition; - }) })); - this.server.setRequestHandler("tools/call", async (request, ctx) => { - const tool = this._registeredTools[request.params.name]; - if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - try { - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, ctx); - await this.validateToolOutput(tool, result, request.params.name); - if (isInputRequiredResult(result)) return result; - return this.server.projectCallToolResult(result, tool.outputSchemaJson); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [{ - type: "text", - text: errorMessage - }], - isError: true - }; - } - /** - * Validates tool input arguments against the tool's input schema. - */ - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) return; - const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); - return parseResult.data; - } - /** - * Validates tool output against the tool's output schema. - */ - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) return; - if (isInputRequiredResult(result)) return; - if (result.isError) return; - if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); - } - /** - * Executes a tool handler. - */ - async executeToolHandler(tool, args, ctx) { - return tool.executor(args, ctx); - } - _completionHandlerInitialized = false; - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) return; - this.server.assertCanSetRequestHandler("completion/complete"); - this.server.registerCapabilities({ completions: {} }); - this.server.setRequestHandler("completion/complete", async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; - const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); - if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; - const completer = getCompleter(field); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - _resourceHandlersInitialized = false; - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) return; - this.server.assertCanSetRequestHandler("resources/list"); - this.server.assertCanSetRequestHandler("resources/templates/list"); - this.server.assertCanSetRequestHandler("resources/read"); - this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); - this.server.setRequestHandler("resources/list", async (_request, ctx) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) continue; - const result = await template.resourceTemplate.listCallback(ctx); - for (const resource of result.resources) templateResources.push({ - ...template.metadata, - ...resource - }); - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler("resources/templates/list", async () => { - return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })) }; - }); - this.server.setRequestHandler("resources/read", async (request, ctx) => { - let uri; - try { - uri = new URL(request.params.uri); - } catch { - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { - uri: request.params.uri, - reason: "invalid_uri" - }); - } - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); - return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); - } - throw new ResourceNotFoundError(request.params.uri); - }); - this._resourceHandlersInitialized = true; - } - _promptHandlersInitialized = false; - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) return; - this.server.assertCanSetRequestHandler("prompts/list"); - this.server.assertCanSetRequestHandler("prompts/get"); - this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); - this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, - icons: prompt.icons, - _meta: prompt._meta - }; - }) })); - this.server.setRequestHandler("prompts/get", async (request, ctx) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - return prompt.handler(request.params.arguments, ctx); - }); - this._promptHandlersInitialized = true; - } - registerResource(name, uriOrTemplate, config, readCallback) { - const cacheHint = config.cacheHint; - let metadata = config; - if (cacheHint !== void 0) { - assertValidCacheHint(cacheHint, `resource ${name}`); - const rest = { ...config }; - delete rest.cacheHint; - metadata = rest; - } - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (updates.uri !== void 0 && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) this._registeredResources[updates.uri] = registeredResource; - } - if (updates.name !== void 0) registeredResource.name = updates.name; - if (updates.title !== void 0) registeredResource.title = updates.title; - if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; - if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; - if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { - let currentArgsSchema = argsSchema; - let currentCallback = callback; - const registeredPrompt = { - title, - description, - argsSchema, - icons, - _meta, - handler: createPromptHandler(name, argsSchema, callback), - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; - } - if (updates.title !== void 0) registeredPrompt.title = updates.title; - if (updates.description !== void 0) registeredPrompt.description = updates.description; - if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; - if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; - let needsHandlerRegen = false; - if (updates.argsSchema !== void 0) { - registeredPrompt.argsSchema = updates.argsSchema; - currentArgsSchema = updates.argsSchema; - needsHandlerRegen = true; - } - if (updates.callback !== void 0) { - currentCallback = updates.callback; - needsHandlerRegen = true; - } - if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); - if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - if (argsSchema) { - const shape = getSchemaShape(argsSchema); - if (shape) { - if (Object.values(shape).some((field) => { - return isCompletable(unwrapOptionalSchema(field)); - })) this.setCompletionRequestHandler(); - } - } - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { - validateAndWarnToolName(name); - if (inputSchema !== void 0) try { - const json = standardSchemaToJsonSchema(inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); - if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); - } catch {} - let currentHandler = handler; - const registeredTool = { - title, - description, - inputSchema, - outputSchema, - outputSchemaJson: convertOutputSchemaJson(outputSchema), - annotations, - icons, - execution, - _meta, - handler, - executor: createToolExecutor(inputSchema, handler), - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - if (typeof updates.name === "string") validateAndWarnToolName(updates.name); - delete this._registeredTools[name]; - delete this._toolInputSchemaJson[name]; - if (updates.name) { - delete this._toolInputSchemaJson[updates.name]; - this._registeredTools[updates.name] = registeredTool; - name = updates.name; - } - } - if (updates.title !== void 0) registeredTool.title = updates.title; - if (updates.description !== void 0) registeredTool.description = updates.description; - let needsExecutorRegen = false; - if (updates.paramsSchema !== void 0) { - registeredTool.inputSchema = updates.paramsSchema; - delete this._toolInputSchemaJson[name]; - needsExecutorRegen = true; - } - if (updates.callback !== void 0) { - registeredTool.handler = updates.callback; - currentHandler = updates.callback; - needsExecutorRegen = true; - } - if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); - if (updates.outputSchema !== void 0) { - registeredTool.outputSchema = updates.outputSchema; - registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); - } - if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; - if (updates.icons !== void 0) registeredTool.icons = updates.icons; - if (updates._meta !== void 0) registeredTool._meta = updates._meta; - if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - registerTool(name, config, cb) { - if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); - const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; - return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); - } - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); - const { title, description, argsSchema, icons, _meta } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns `true` if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" - * await server.sendLoggingMessage({ - * level: 'info', - * data: 'Processing complete' - * }); - * ``` - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) this.server.sendResourceListChanged(); - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) this.server.sendToolListChanged(); - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) this.server.sendPromptListChanged(); - } -}; -/** -* A resource template combines a URI pattern with optional functionality to enumerate -* all resources matching that pattern. -*/ -var ResourceTemplate = class { - _uriTemplate; - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - return this._callbacks.complete?.[variable]; - } -}; -/** -* Creates an executor that invokes the handler with the appropriate arguments. -* When `inputSchema` is defined, the handler is called with `(args, ctx)`. -* When `inputSchema` is undefined, the handler is called with just `(ctx)`. -*/ -function createToolExecutor(inputSchema, handler) { - if (inputSchema) { - const callback$1 = handler; - return async (args, ctx) => callback$1(args, ctx); - } - const callback = handler; - return async (_args, ctx) => callback(ctx); -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -/** -* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} -* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that -* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion -* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). -*/ -function convertOutputSchemaJson(outputSchema) { - if (outputSchema === void 0) return void 0; - try { - return standardSchemaToJsonSchema(outputSchema, "output"); - } catch { - return; - } -} -/** -* Creates a type-safe prompt handler that captures the schema and callback in a closure. -* This eliminates the need for type assertions at the call site. -*/ -function createPromptHandler(name, argsSchema, callback) { - if (argsSchema) { - const typedCallback = callback; - return async (args, ctx) => { - const parseResult = await validateStandardSchema(argsSchema, args); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); - return typedCallback(parseResult.data, ctx); - }; - } else { - const typedCallback = callback; - return async (_args, ctx) => { - return typedCallback(ctx); - }; - } -} -function createCompletionResult(suggestions) { - return { completion: { - values: suggestions.map(String).slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } }; -} -const EMPTY_COMPLETION_RESULT = { completion: { - values: [], - hasMore: false -} }; -/** @internal Gets the shape of a Zod object schema */ -function getSchemaShape(schema) { - const candidate = schema; - if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; -} -/** @internal Checks if a Zod schema is optional */ -function isOptionalSchema(schema) { - return schema?.type === "optional"; -} -/** @internal Unwraps an optional Zod schema */ -function unwrapOptionalSchema(schema) { - if (!isOptionalSchema(schema)) return schema; - return schema.def?.innerType ?? schema; -} - -//#endregion - -//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map - - - - -//#region src/server/perRequestTransport.ts -/** -* The per-request micro-transport: a real, connected `Transport` whose whole -* lifetime is one HTTP exchange. See the module documentation for the -* response shapes it produces. -*/ -var PerRequestHTTPServerTransport = class { - onclose; - onerror; - onmessage; - _classification; - _responseMode; - _started = false; - _used = false; - _closed = false; - _terminalDelivered = false; - /** - * `true` only while the inbound message is being delivered synchronously - * to the connected protocol layer. The pre-handler gates (the era - * registry gate, the edge→instance handoff check, the missing-handler - * rejection) answer inside this window; request handlers always run - * after it (the protocol layer defers them to a microtask). An error - * sent inside the window is therefore ladder-originated, and an error - * sent after it is handler-produced. - */ - _dispatchWindowOpen = false; - _requestId; - _deferredResponse; - _sse; - _abortCleanup; - _keepAliveMs; - constructor(options) { - this._classification = options.classification; - this._responseMode = options.responseMode ?? "auto"; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - async start() { - if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); - this._started = true; - } - /** - * Serves the single exchange: delivers the classified message to the - * connected server instance and resolves with the HTTP response. - * - * Throws when called a second time (the transport is strictly - * single-use), or before a server has been connected to the transport. - * The returned promise rejects with a connection-closed error when the - * transport is closed before a response was produced (for example because - * the client disconnected). - */ - async handleMessage(message, extra) { - if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); - if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); - if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); - this._used = true; - const signal = extra?.request?.signal; - if (signal?.aborted) { - await this.close(); - throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); - } - const messageExtra = { - classification: this._classification, - ...extra?.request !== void 0 && { request: extra.request }, - ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } - }; - if (isJSONRPCRequest(message)) { - this._requestId = message.id; - let resolve; - let reject; - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve; - reject = promiseReject; - }); - this._deferredResponse = { - promise, - resolve, - reject, - settled: false - }; - if (signal !== void 0) { - const onAbort = () => void this.close(); - signal.addEventListener("abort", onAbort, { once: true }); - this._abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - this._dispatchWindowOpen = true; - try { - this.onmessage(message, messageExtra); - } finally { - this._dispatchWindowOpen = false; - } - if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); - return promise; - } - this.onmessage(message, messageExtra); - return new Response(null, { status: 202 }); - } - async send(message, options) { - if (this._closed) return; - const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); - const relatedId = isResponse ? message.id : options?.relatedRequestId; - if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { - if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); - return; - } - if (isResponse) { - if (this._terminalDelivered) return; - this._terminalDelivered = true; - const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; - const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; - if (ladderStatus !== void 0 && this._sse === void 0) { - this.settleResponse(Response.json(message, { - status: ladderStatus, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._sse !== void 0 || this._responseMode === "sse") { - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - this.finalizeStream(); - return; - } - this.settleResponse(Response.json(message, { - status: 200, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._responseMode === "json") return; - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - } - /** - * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the - * exchange is not currently streaming. - */ - writeCommentFrame(comment) { - if (this._closed || this._sse === void 0 || this._sse.closed) return; - const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); - this.writeFrame(`${frame}\n\n`); - } - async close() { - if (this._closed) return; - this._closed = true; - this._abortCleanup?.(); - this._abortCleanup = void 0; - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { - this._deferredResponse.settled = true; - this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); - } - this.onclose?.(); - } - settleResponse(response) { - if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; - this._deferredResponse.settled = true; - this._deferredResponse.resolve(response); - } - upgradeToSse() { - let controller; - const readable = new ReadableStream({ - start: (streamController) => { - controller = streamController; - }, - cancel: () => { - this.close(); - } - }); - this._sse = { - controller, - encoder: new TextEncoder(), - closed: false - }; - this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); - this.settleResponse(new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - })); - } - finalizeStream() { - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - queueMicrotask(() => void this.close()); - } - writeMessageFrame(message) { - this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - writeFrame(frame) { - if (this._sse === void 0 || this._sse.closed) return; - try { - this._sse.controller.enqueue(this._sse.encoder.encode(frame)); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); - } - } -}; - -//#endregion -//#region src/server/invoke.ts -/** -* Serves one classified inbound message on the given server instance and -* returns the HTTP response for the exchange. -* -* The instance is connected to a fresh single-exchange transport, the message -* is injected through the normal transport message path, and whatever the -* dispatch layer produces (the handler result, a protocol-level rejection, or -* streamed related messages followed by the result) is captured as the -* returned `Response`. For request exchanges, teardown rides the transport's -* close chain once the terminal response has been delivered; notification -* exchanges resolve with the 202 response immediately and do NOT run the -* close chain — the transport stays connected until the caller closes it or -* drops the per-request instance, which is the caller's choice either way. -*/ -async function invoke(server, message, ctx) { - const transport = new PerRequestHTTPServerTransport({ - classification: ctx.classification, - ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, - ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } - }); - await server.connect(transport); - return transport.handleMessage(message, { - ...ctx.request !== void 0 && { request: ctx.request }, - ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } - }); -} - -//#endregion -//#region src/server/streamableHttp.ts -/** -* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification -* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). -* -* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. -* -* In stateful mode: -* - Session ID is generated and included in response headers -* - Session ID is always included in initialization responses -* - Requests with invalid session IDs are rejected with `404 Not Found` -* - Non-initialization requests without a session ID are rejected with `400 Bad Request` -* - State is maintained in-memory (connections, message history) -* -* In stateless mode: -* - No Session ID is included in any responses -* - No session validation is performed -* -* @example Stateful setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: () => crypto.randomUUID() -* }); -* -* await server.connect(transport); -* ``` -* -* @example Stateless setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: undefined -* }); -* ``` -* -* @example Hono.js -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" -* app.all('/mcp', async c => { -* return transport.handleRequest(c.req.raw); -* }); -* ``` -* -* @example Cloudflare Workers -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" -* const worker = { -* async fetch(request: Request): Promise { -* return transport.handleRequest(request); -* } -* }; -* ``` -*/ -var WebStandardStreamableHTTPServerTransport = class { - sessionIdGenerator; - _started = false; - _closed = false; - _streamMapping = /* @__PURE__ */ new Map(); - _requestToStreamMapping = /* @__PURE__ */ new Map(); - _requestResponseMap = /* @__PURE__ */ new Map(); - _initialized = false; - _enableJsonResponse = false; - _standaloneSseStreamId = "_GET_stream"; - _eventStore; - _onsessioninitialized; - _onsessionclosed; - _allowedHosts; - _allowedOrigins; - _enableDnsRebindingProtection; - _retryInterval; - _supportedProtocolVersions; - _keepAliveMs; - sessionId; - onclose; - onerror; - onmessage; - constructor(options = {}) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - this._retryInterval = options.retryInterval; - this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - startKeepAlive(controller, encoder) { - if (this._closed) return void 0; - const timer = armSseKeepAlive(this._keepAliveMs, () => { - try { - controller.enqueue(encoder.encode(": keepalive\n\n")); - } catch { - if (timer !== void 0) clearInterval(timer); - } - }); - return timer; - } - /** - * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) throw new Error("Transport already started"); - this._started = true; - } - /** - * Sets the supported protocol versions for header validation. - * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. - */ - setSupportedProtocolVersions(versions) { - this._supportedProtocolVersions = versions; - } - /** - * Helper to create a JSON error response - */ - createJsonErrorResponse(status, code, message, options) { - const error = { - code, - message - }; - if (options?.data !== void 0) error.data = options.data; - return Response.json({ - jsonrpc: "2.0", - error, - id: null - }, { - status, - headers: { - "Content-Type": "application/json", - ...options?.headers - } - }); - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error response if validation fails, `undefined` if validation passes. - */ - validateRequestHeaders(req) { - if (!this._enableDnsRebindingProtection) return; - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.get("host"); - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - const error = `Invalid Host header: ${hostHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.get("origin"); - if (originHeader && !this._allowedOrigins.includes(originHeader)) { - const error = `Invalid Origin header: ${originHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - } - /** - * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` - * Returns a `Response` object (Web Standard) - */ - async handleRequest(req, options) { - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const validationError = this.validateRequestHeaders(req); - if (validationError) return validationError; - switch (req.method) { - case "POST": return this.handlePostRequest(req, options); - case "GET": return this.handleGetRequest(req); - case "DELETE": return this.handleDeleteRequest(req); - default: return this.handleUnsupportedRequest(); - } - } - /** - * Returns true if the client's protocol version supports empty SSE data in - * priming events (the fix shipped with protocol version `2025-11-25`). - * - * The version is checked for membership in this transport instance's - * supported protocol versions rather than with an open-ended - * `>= '2025-11-25'` comparison: the value may come from an `initialize` - * request body, which (unlike the `MCP-Protocol-Version` header) is not - * validated against `supportedProtocolVersions` before reaching this - * check. An unknown future version string must not silently enable - * behavior reserved for versions this transport actually supports. - */ - supportsEmptySSEData(protocolVersion) { - return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; - } - /** - * Writes a priming event to establish resumption capability. - * Only sends if `eventStore` is configured (opt-in for resumability) and - * the client's protocol version supports empty SSE data (a supported - * version that is >= `2025-11-25`). - */ - async writePrimingEvent(controller, encoder, streamId, protocolVersion) { - if (!this._eventStore) return; - if (!this.supportsEmptySSEData(protocolVersion)) return; - const primingEventId = await this._eventStore.storeEvent(streamId, {}); - let primingEvent = `id: ${primingEventId}\ndata: \n\n`; - if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; - controller.enqueue(encoder.encode(primingEvent)); - } - /** - * Handles `GET` requests for SSE stream - */ - async handleGetRequest(req) { - if (!req.headers.get("accept")?.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); - } - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - if (this._eventStore) { - const lastEventId = req.headers.get("last-event-id"); - if (lastEventId) return this.replayEvents(lastEventId); - } - if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); - } - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - this._streamMapping.set(this._standaloneSseStreamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(this._standaloneSseStreamId); - try { - streamController.close(); - } catch {} - } - }); - keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId) { - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); - return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); - } - try { - let streamId; - if (this._eventStore.getStreamIdForEventId) { - streamId = await this._eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); - return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); - } - if (this._streamMapping.get(streamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); - } - } - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - let cancelled = false; - let replayedStreamId; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - cancelled = true; - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); - } - }); - const replayedEventIds = /* @__PURE__ */ new Set(); - replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { - replayedEventIds.add(eventId); - if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { - streamController.close(); - } catch {} - } }); - if (this._closed || cancelled) { - try { - streamController.close(); - } catch {} - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - this._streamMapping.get(replayedStreamId)?.cleanup(); - this._streamMapping.set(replayedStreamId, { - controller: streamController, - encoder, - replayedEventIds, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - }); - if (replayedStreamId !== this._standaloneSseStreamId) { - if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - } - if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); - } - } - /** - * Writes an event to an SSE stream via controller with proper formatting - */ - writeSSEEvent(controller, encoder, message, eventId) { - try { - let eventData = `event: message\n`; - if (eventId) eventData += `id: ${eventId}\n`; - eventData += `data: ${JSON.stringify(message)}\n\n`; - controller.enqueue(encoder.encode(eventData)); - return true; - } catch (error) { - this.onerror?.(error); - return false; - } - } - /** - * Handles unsupported requests (`PUT`, `PATCH`, etc.) - */ - handleUnsupportedRequest() { - this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: "Method not allowed." - }, - id: null - }, { - status: 405, - headers: { - Allow: "GET, POST, DELETE", - "Content-Type": "application/json" - } - }); - } - /** - * Handles `POST` requests containing JSON-RPC messages - */ - async handlePostRequest(req, options) { - try { - const acceptHeader = req.headers.get("accept"); - if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); - } - if (!isJsonContentType(req.headers.get("content-type"))) { - this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const request = req; - let rawMessage; - if (options?.parsedBody === void 0) try { - rawMessage = await req.json(); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); - } - else rawMessage = options.parsedBody; - let messages; - try { - messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); - if (isInitializationRequest) { - if (this._initialized && this.sessionId !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); - } - if (messages.length > 1) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - if (!isInitializationRequest) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - if (!messages.some((element) => isJSONRPCRequest(element))) { - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - return new Response(null, { status: 202 }); - } - const streamId = crypto.randomUUID(); - const initRequest = messages.find((m) => isInitializeRequest(m)); - const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (this._enableJsonResponse) return new Promise((resolve) => { - this._streamMapping.set(streamId, { - resolveJson: resolve, - cleanup: () => { - this._streamMapping.delete(streamId); - } - }); - for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - }); - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - for (const message of messages) if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(streamId); - try { - streamController.close(); - } catch {} - } - }); - this._requestToStreamMapping.set(message.id, streamId); - } - await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); - for (const message of messages) { - let closeSSEStream; - let closeStandaloneSSEStream; - if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { - closeSSEStream = () => { - this.closeSSEStream(message.id); - }; - closeStandaloneSSEStream = () => { - this.closeStandaloneSSEStream(); - }; - } - this.onmessage?.(message, { - authInfo: options?.authInfo, - request, - closeSSEStream, - closeStandaloneSSEStream - }); - } - if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { - status: 200, - headers - }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); - } - } - /** - * Handles `DELETE` requests to terminate sessions - */ - async handleDeleteRequest(req) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - try { - await Promise.resolve(this._onsessionclosed?.(this.sessionId)); - return new Response(null, { status: 200 }); - } finally { - await this.close(); - } - } - /** - * Validates session ID for non-initialization requests. - * Returns `Response` error if invalid, `undefined` otherwise - */ - validateSession(req) { - if (this.sessionIdGenerator === void 0) return; - if (!this._initialized) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); - } - const sessionId = req.headers.get("mcp-session-id"); - if (!sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); - } - if (sessionId !== this.sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Session not found")); - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - } - /** - * Validates the `MCP-Protocol-Version` header on incoming requests. - * - * For initialization: Version negotiation handles unknown versions gracefully - * (server responds with its supported version). - * - * For subsequent requests with `MCP-Protocol-Version` header: - * - Accept if in supported list - * - 400 if unsupported - * - * For HTTP requests without the `MCP-Protocol-Version` header: - * - Accept and default to the version negotiated at initialization - */ - validateProtocolVersion(req) { - const protocolVersion = req.headers.get("mcp-protocol-version"); - if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { - const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(400, -32e3, error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - for (const { cleanup } of this._streamMapping.values()) cleanup(); - this._streamMapping.clear(); - this._requestResponseMap.clear(); - this.onclose?.(); - } - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId) { - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) return; - const stream = this._streamMapping.get(streamId); - if (stream) stream.cleanup(); - } - /** - * Close the standalone `GET` SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream() { - const stream = this._streamMapping.get(this._standaloneSseStreamId); - if (stream) stream.cleanup(); - } - async send(message, options) { - let requestId = options?.relatedRequestId; - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; - if (requestId === void 0) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); - let eventId; - if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === void 0) return; - if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); - return; - } - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); - let stream = this._streamMapping.get(streamId); - if (!this._enableJsonResponse) { - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - stream = this._streamMapping.get(streamId); - } - if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); - } - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); - if (relatedIds.every((id) => this._requestResponseMap.has(id))) { - if (!stream) { - if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - if (this._enableJsonResponse && stream.resolveJson) { - const headers = { "Content-Type": "application/json" }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); - if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { - status: 200, - headers - })); - else stream.resolveJson(Response.json(responses, { - status: 200, - headers - })); - stream.cleanup(); - } else stream.cleanup(); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -}; - -//#endregion -//#region src/server/createMcpHandler.ts -/** -* The JSON-RPC id to echo on an entry-built error response: the body's `id` -* when the body is a single JSON-RPC request whose id is a string or number, -* `null` otherwise. Error responses must carry the id of the request they -* correspond to whenever it could be read; `null` is reserved for the cases -* where no single request id is determinable — unparseable bodies, body-less -* methods, notifications, posted responses and batch arrays. -*/ -function echoableRequestId(body) { - if (body === null || typeof body !== "object" || Array.isArray(body)) return null; - const { method, id } = body; - if (typeof method !== "string") return null; - return typeof id === "string" || typeof id === "number" ? id : null; -} -function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message, - ...data !== void 0 && { data } - }, - id - }, { status: httpStatus }); -} -function rejectionResponse(rejection, id = null) { - return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); -} -function toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} -function internalServerErrorResponse(id = null) { - return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); -} -/** -* The entry's default legacy serving (`legacy: 'stateless'`): per-request -* stateless serving of 2025-era traffic using the same factory as the modern -* path. Exported as a standalone building block for hand-wired compositions -* (for example mounting legacy stateless serving on its own route next to a -* strict modern endpoint). -* -* Each POST is served by a fresh instance from the factory connected to a -* fresh streamable HTTP transport constructed with only -* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. -* Because serving is per-request and stateless, GET and DELETE (2025 session -* operations) are answered with `405` / `Method not allowed.`, exactly like the -* canonical stateless example. -* -* The optional `onerror` callback receives factory and serving failures on -* this leg (reporting only — the response stays the 500 internal-error body). -* The entry passes its own `onerror` here when expanding the default, so -* legacy-leg failures are never silently swallowed. -*/ -function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { - return async (request, options) => { - if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); - try { - const product = await factory({ - era: "legacy", - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - requestInfo: request - }); - const transport = new WebStandardStreamableHTTPServerTransport({ - sessionIdGenerator: void 0, - ...keepAliveMs !== void 0 && { keepAliveMs } - }); - await product.connect(transport); - const teardown = () => { - transport.close().catch(() => {}); - product.close().catch(() => {}); - }; - request.signal?.addEventListener("abort", teardown, { once: true }); - const response = await transport.handleRequest(request, { - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } - }); - if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { - teardown(); - return response; - } - const reader = response.body.getReader(); - let toreDown = false; - const completeExchange = () => { - if (!toreDown) { - toreDown = true; - teardown(); - } - }; - const monitoredBody = new ReadableStream({ - pull: async (controller) => { - try { - const { done, value } = await reader.read(); - if (done) { - completeExchange(); - controller.close(); - return; - } - if (value !== void 0) controller.enqueue(value); - } catch (error) { - completeExchange(); - controller.error(error); - } - }, - cancel: (reason) => { - completeExchange(); - return reader.cancel(reason).catch(() => {}); - } - }); - return new Response(monitoredBody, { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } catch (error) { - try { - onerror?.(toError(error)); - } catch {} - return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); - } - }; -} -function legacyStatelessFallback(factory, onerror) { - return createLegacyStatelessFallback(factory, onerror); -} -/** -* The entry's classification step: read the request body exactly once (unless -* a pre-parsed body is supplied) and classify the request with -* {@linkcode classifyInboundRequest}. This is the single code path behind both -* {@linkcode createMcpHandler}'s routing and the exported -* {@linkcode isLegacyRequest} predicate, so the two can never disagree. -* -* Pass `needsForward: false` when the caller never reads `forwardRequest` — -* the body-preserving clone is then skipped and `forwardRequest` is the -* (consumed) input request. -*/ -async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { - const httpMethod = request.method.toUpperCase(); - let body; - let parsedBody = providedParsedBody; - let forwardRequest = request; - let unparseable = false; - if (httpMethod === "POST") { - if (parsedBody === void 0) { - if (needsForward) forwardRequest = request.clone(); - let bodyText; - try { - bodyText = await request.text(); - } catch { - return { step: "unreadable-body" }; - } - try { - body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); - } catch { - unparseable = true; - } - if (!unparseable && body !== void 0) parsedBody = body; - } else body = parsedBody; - if (unparseable || body === void 0) return { - step: "no-json-body", - forwardRequest - }; - } - return { - step: "classified", - outcome: classifyInboundRequest({ - httpMethod, - protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0, - ...body !== void 0 && { body } - }), - body, - parsedBody, - forwardRequest - }; -} -/** -* Whether {@linkcode createMcpHandler} would route this request to its legacy -* (2025-era) serving rather than the modern (2026-07-28) path. -* -* Call it with just the request: `await isLegacyRequest(request)`. For a -* `POST` the body is read from an internal clone, so the request you pass -* stays fully readable for whichever handler you route it to — no second -* argument is needed. (In a Node `(req, res)` handler, build that `Request` -* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body -* parser, which has already drained the Node stream, build it as -* `toWebRequest(req, req.body)` so the bytes come from the parsed body — -* either way the predicate still takes just the request.) The optional -* `parsedBody` is a perf escape hatch for a body you already hold parsed: -* pass it and the predicate classifies from the value directly, reading and -* cloning nothing. It is needed, not just faster, when the request's own -* body was already read — the internal clone is then impossible (cloning a -* used body throws a `TypeError`), so such a single-argument call rejects -* instead of guessing. -* -* This is the entry's own classification step exported as a predicate — it -* runs exactly the code `createMcpHandler` runs to make the routing decision, -* not a re-implementation — so a hand-wired composition that branches on it -* can never disagree with the entry. It is classification only: hand-wired -* compositions must validate Content-Type themselves (415 for POSTs whose -* media type is not `application/json`, via {@linkcode isJsonContentType}) -* before dispatching either leg — routing the legacy leg into the SDK -* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy -* deployment (for example a sessionful streamable HTTP wiring) serving 2025 -* traffic next to a strict modern endpoint, now that the entry has no -* handler-valued `legacy` option: -* -* ```ts -* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; -* -* const modern = createMcpHandler(factory, { legacy: 'reject' }); -* -* export default { -* async fetch(request: Request): Promise { -* if (await isLegacyRequest(request)) { -* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring -* return myExistingLegacyHandler(request); -* } -* return modern.fetch(request); -* } -* }; -* ``` -* -* Semantics (identical to the entry's routing): -* -* - Returns `true` only for requests with no per-request `_meta` envelope -* claim: claim-less POSTs (including the `initialize` handshake and 2025-era -* notification POSTs without a modern protocol-version header), body-less -* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted -* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. -* - Returns `false` for everything the modern path answers, including its -* validation-ladder rejections: a request carrying the envelope claim (even -* one naming a revision the endpoint does not serve — the modern path -* answers it with the unsupported-protocol-version error), a malformed -* envelope behind a present claim (answered `-32602`), a request whose -* `MCP-Protocol-Version` header names a modern revision but that lacks the -* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers -* routing on the predicate must send `false` traffic to the modern handler, -* never to a legacy handler — the modern path owns those error answers. -* - `server/discover` probes sent by negotiating clients always carry the -* envelope claim, so they are never legacy; a hand-built claim-less POST to -* a method named `server/discover` has no claim and classifies legacy, -* exactly as the entry itself routes it. -*/ -async function isLegacyRequest(request, parsedBody) { - const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); - return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; -} -/** -* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a -* per-request server factory and, by default, falls back to old-school -* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a -* modern-only strict endpoint. -* -* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, -* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap -* the handler once with `toNodeHandler(handler)` from -* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, -* put Origin/Host validation in front of the handler — the entry itself is -* deliberately validation-free: -* -* ```ts -* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; -* -* export default { -* async fetch(request: Request): Promise { -* const rejected = -* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? -* originValidationResponse(request, localhostAllowedOrigins()); -* return rejected ?? handler.fetch(request); -* } -* }; -* ``` -* -* Use ONE factory for both legs: the same tools/resources/prompts definition -* backs the modern path and the stateless legacy fallback, so the two eras can -* never drift apart. To keep an existing legacy deployment (for example a -* sessionful streamable HTTP wiring) serving 2025 traffic instead of the -* stateless fallback, route in user land with {@linkcode isLegacyRequest} in -* front of a strict handler — see that predicate's documentation for the -* pattern. Power users composing transport-neutral routing can also use the -* exported building blocks directly: {@linkcode classifyInboundRequest} for -* the era decision and `PerRequestHTTPServerTransport` for single-exchange -* serving — such compositions must reject POSTs whose Content-Type media type -* is not `application/json` (415) before parsing the body, using -* {@linkcode isJsonContentType}; neither building block performs this -* validation itself. -* -* The entry performs no token verification: `authInfo` given to `fetch` is -* passed through to handlers and the factory as-is and is never derived from -* request headers. -*/ -function createMcpHandler(factory, options = {}) { - const { legacy, onerror, responseMode } = options; - if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); - /** Modern per-request instances with an exchange still in flight (close() tears these down). */ - const inflight = /* @__PURE__ */ new Set(); - let closed = false; - const reportError = (error) => { - try { - onerror?.(error); - } catch {} - }; - const bus = options.bus ?? new InMemoryServerEventBus(reportError); - const notify = createServerNotifier(bus); - const listenRouter = createListenRouter({ - bus, - maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, - keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, - onerror: reportError - }); - if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); - const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); - async function serveModern(route, request, authInfo) { - const claimedRevision = route.classification.revision; - if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedRevision ?? "unknown" - }); - reportError(error); - return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); - } - const stdHeaderRejection = validateStandardRequestHeaders({ - httpMethod: request.method, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0 - }, route); - if (stdHeaderRejection !== void 0) { - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); - return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); - } - const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; - const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; - if (route.messageKind === "request") { - const required = requiredClientCapabilitiesForRequest(route.message.method); - if (required !== void 0) { - const missing = missingClientCapabilities(required, declaredClientCapabilities); - if (missing !== void 0) { - const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); - reportError(error); - return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); - } - } - } - const product = await factory({ - era: "modern", - ...authInfo !== void 0 && { authInfo }, - requestInfo: request - }); - const server = product instanceof McpServer ? product.server : product; - if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { - const capabilities = server.getCapabilities(); - const serverInfo = serverIdentityOf(server); - product.close().catch(reportError); - return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); - } - if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { - const callParams = route.message.params; - const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; - const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); - if (inputSchema !== void 0) { - const scan = scanXMcpHeaderDeclarations(inputSchema); - if (scan.valid && scan.declarations.length > 0) { - const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); - if (rejection !== void 0) { - product.close().catch(reportError); - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); - return rejectionResponse(rejection, route.message.id); - } - } - } - } - setNegotiatedProtocolVersion(server, claimedRevision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (meta !== void 0) seedClientIdentityFromEnvelope(server, { - clientInfo: meta[CLIENT_INFO_META_KEY], - clientCapabilities: declaredClientCapabilities - }); - const previousOnClose = server.onclose; - inflight.add(server); - server.onclose = () => { - inflight.delete(server); - previousOnClose?.(); - }; - try { - const response = await invoke(product, route.message, { - classification: route.classification, - request, - ...authInfo !== void 0 && { authInfo }, - ...responseMode !== void 0 && { responseMode }, - ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } - }); - if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); - return response; - } catch (error) { - if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); - await server.close().catch(() => {}); - inflight.delete(server); - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(route.message)); - } - } - async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { - if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { - ...authInfo !== void 0 && { authInfo }, - ...parsedBody !== void 0 && { parsedBody } - }); - const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (strict === void 0) return new Response(null, { status: 202 }); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); - return rejectionResponse(strict, echoableRequestId(parsedBody)); - } - async function handle(request, requestOptions) { - const authInfo = requestOptions?.authInfo; - if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { - reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); - if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); - if (classified.step === "no-json-body") { - if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); - return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); - } - const { outcome, body, parsedBody, forwardRequest } = classified; - try { - switch (outcome.kind) { - case "reject": - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); - return rejectionResponse(outcome, echoableRequestId(body)); - case "modern": return await serveModern(outcome, request, authInfo); - case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); - } - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(body)); - } - } - const fetchFace = async (request, requestOptions) => { - if (closed) throw new Error("This MCP handler has been closed"); - try { - return await handle(request, requestOptions); - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); - } - }; - return { - fetch: fetchFace, - notify, - bus, - close: async () => { - closed = true; - listenRouter.closeAll(); - const closing = [...inflight].map((server) => server.close().catch(() => {})); - inflight.clear(); - await Promise.all(closing); - } - }; -} - -//#endregion -//#region src/server/middleware/bearerAuth.ts -function headerQuotedValue(value) { - return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); -} -function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { - let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; - if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; - if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; - return header; -} -/** -* Validate a raw `Authorization` header value as a Bearer token and return -* the verified {@link AuthInfo}. -* -* The runtime-neutral core of Bearer authentication: it parses the header, -* runs the verifier, enforces `requiredScopes`, and rejects tokens without an -* expiration or past it. On any failure it throws an {@link OAuthError} — -* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP -* answer, or use {@link requireBearerAuth} to get both steps as one call. -* -* Framework adapters build on this: `requireBearerAuth` from -* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. -*/ -async function verifyBearerToken(authorizationHeader, options) { - const { verifier, requiredScopes = [] } = options; - if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); - const [type, token] = authorizationHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); - const authInfo = await verifier.verifyAccessToken(token); - if (requiredScopes.length > 0) { - if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); - } - if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); - else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); - return authInfo; -} -/** -* Build the HTTP answer for a Bearer authentication failure. -* -* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and -* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` -* challenge, with `resource_metadata` when configured so clients can discover -* the Authorization Server), `500` for `server_error`, `400` for anything -* else. A non-`OAuthError` value answers `500 server_error`. The body is the -* OAuth error JSON. -*/ -function bearerAuthChallengeResponse(error, options) { - const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; - if (!(error instanceof OAuthError)) { - const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); - return Response.json(serverError.toResponseObject(), { status: 500 }); - } - switch (error.code) { - case OAuthErrorCode.InvalidToken: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 401, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.InsufficientScope: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 403, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); - default: return Response.json(error.toResponseObject(), { status: 400 }); - } -} -/** -* Require a valid Bearer token on web-standard requests. -* -* The framework-free counterpart of `requireBearerAuth` from -* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a -* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The -* returned gate resolves to the verified {@link AuthInfo}, or to the -* ready-to-return challenge `Response` when the request must be refused. -* -* @example -* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" -* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); -* -* async function fetchHandler(request: Request): Promise { -* const auth: AuthInfo | Response = await gate(request); -* if (auth instanceof Response) return auth; -* return handler.fetch(request, { authInfo: auth }); -* } -* ``` -*/ -function requireBearerAuth(options) { - const { verifier, requiredScopes = [], resourceMetadataUrl } = options; - const resolved = { - verifier, - requiredScopes, - resourceMetadataUrl - }; - return async (request) => { - const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); - try { - return await verifyBearerToken(authorizationHeader || void 0, resolved); - } catch (error) { - return bearerAuthChallengeResponse(error, resolved); - } - }; -} - -//#endregion -//#region src/server/middleware/hostHeaderValidation.ts -/** -* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). -* -* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). -* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). -*/ -function validateHostHeader(hostHeader, allowedHostnames) { - if (!hostHeader) return { - ok: false, - errorCode: "missing_host", - message: "Missing Host header" - }; - let hostname; - try { - hostname = new URL(`http://${hostHeader}`).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_host_header", - message: `Invalid Host header: ${hostHeader}`, - hostHeader - }; - } - if (!allowedHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_host", - message: `Invalid Host: ${hostname}`, - hostHeader, - hostname - }; - return { - ok: true, - hostname - }; -} -/** -* Convenience allowlist for `localhost` DNS rebinding protection. -*/ -function localhostAllowedHostnames() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for DNS rebinding protection. -* @example -* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" -* const result = validateHostHeader(req.headers.get('host'), ['localhost']); -* ``` -*/ -function hostHeaderValidationResponse(req, allowedHostnames) { - const result = validateHostHeader(req.headers.get("host"), allowedHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/middleware/oauthMetadata.ts -function checkIssuerUrl(issuer, allowInsecure) { - if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); - if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); -} -/** -* Derive the RFC 9728 Protected Resource Metadata document from -* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL -* (HTTPS required outside localhost) in the process. -* -* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build -* on this; use it directly when serving the document through your own -* routing — or call it once at startup to fail fast on a misconfigured -* issuer before any request arrives. -*/ -function buildOAuthProtectedResourceMetadata(options) { - checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); - return { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: options.serviceDocumentationUrl?.href - }; -} -/** -* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server -* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. -* -* @example -* ```ts -* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) -* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' -* ``` -*/ -function getOAuthProtectedResourceMetadataUrl(serverUrl) { - return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; -} -/** The RFC 9728 path-aware well-known path for a resource URL. */ -function protectedResourceMetadataPath(resourceServerUrl) { - const rsPath = stripTrailingSlash(resourceServerUrl.pathname); - return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; -} -function stripTrailingSlash(path) { - return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; -} -const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; -function metadataDocumentResponse(request, metadata) { - if (request.method === "OPTIONS") { - const requestedHeaders = request.headers.get("access-control-request-headers"); - return new Response(null, { - status: 204, - headers: { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": ALLOWED_METHODS, - ...requestedHeaders === null ? {} : { - "Access-Control-Allow-Headers": requestedHeaders, - Vary: "Access-Control-Request-Headers" - } - } - }); - } - if (request.method !== "GET" && request.method !== "HEAD") { - const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); - return Response.json(error.toResponseObject(), { - status: 405, - headers: { - Allow: ALLOWED_METHODS, - "Access-Control-Allow-Origin": "*" - } - }); - } - const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); - return request.method === "HEAD" ? new Response(null, { - status: response.status, - headers: response.headers - }) : response; -} -/** -* Serve the two OAuth discovery documents an MCP server acting as a Resource -* Server exposes, from a web-standard `fetch(request)` handler: -* -* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected -* Resource Metadata, derived from the supplied options (path-aware: the -* resource URL's path is reflected in the route). -* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization -* Server Metadata, passed through verbatim. -* -* Returns the matched document `Response` (JSON with permissive CORS, `405` -* with an `Allow` header for non-GET methods, `204` for CORS preflight), or -* `undefined` when the request path is neither well-known route — fall -* through to your own routing. The framework-free counterpart of -* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with -* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so -* unauthenticated clients can discover the AS from the `401` challenge. -* -* @example -* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" -* async function fetchHandler(request: Request): Promise { -* return oauthMetadataResponse(request, options) ?? serveMcp(request); -* } -* ``` -*/ -function oauthMetadataResponse(request, options) { - const requestPath = stripTrailingSlash(new URL(request.url).pathname); - if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); - if (requestPath === "/.well-known/oauth-authorization-server") { - buildOAuthProtectedResourceMetadata(options); - return metadataDocumentResponse(request, options.oauthMetadata); - } -} - -//#endregion -//#region src/server/middleware/originValidation.ts -/** -* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). -* -* - A missing/empty `Origin` header passes: non-browser clients do not send one, -* and only browser-originated requests carry the header this check defends against. -* - Allowlist items are hostnames only (no scheme, no port), the same convention as -* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). -* - Any present value that cannot be parsed as an origin URL — including the literal -* `null` origin browsers send for opaque contexts — is rejected (deny on failure). -*/ -function validateOriginHeader(originHeader, allowedOriginHostnames) { - if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; - let hostname; - try { - hostname = new URL(originHeader).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - } - if (hostname === "") return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - if (!allowedOriginHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_origin", - message: `Invalid Origin: ${hostname}`, - originHeader, - hostname - }; - return { - ok: true, - origin: originHeader, - hostname - }; -} -/** -* Convenience allowlist of localhost-class origin hostnames, mirroring -* `localhostAllowedHostnames`. -*/ -function localhostAllowedOrigins() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC -* error response when the request's `Origin` header is not allowed, and -* `undefined` when the request may proceed. -* -* ```ts -* const rejected = originValidationResponse(request, localhostAllowedOrigins()); -* if (rejected) return rejected; -* ``` -*/ -function originValidationResponse(req, allowedOriginHostnames) { - const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/requestStateCodec.ts -const PREFIX = "v1."; -function bytesToBase64Url(bytes) { - let bin = ""; - for (const b of bytes) bin += String.fromCodePoint(b); - return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); -} -function constantTimeTagEqual(a, b) { - if (a.length !== b.length) return false; - let r = 0; - for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); - return r === 0; -} -function base64UrlToBytes(s) { - const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return bytes; -} -/** -* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` -* (protocol revision 2026-07-28). -* -* `requestState` round-trips through the client and is attacker-controlled -* input on re-entry. The SDK applies no protection of its own; this helper is -* the convenience implementation of the spec's integrity MUST so authors don't -* hand-roll HMAC. Wire shape: -* -* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) -* -* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` -* — the binding value is never embedded raw. -* -* The codec is **signed, not encrypted**: the body is integrity-protected but -* the client can base64url-decode it and read the payload (`p`) in clear. Do -* not put secrets in the payload; use an AEAD construction if confidentiality -* is required. The handler reads its payload back via the typed -* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` -* (integrity proven, payload decoded) by the time the handler is entered. -* -* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for -* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). -* See `examples/mrtr/server.ts` for a worked end-to-end example. -* -* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference -* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and -* derives independent cipher / bind-HMAC sub-keys from the operator secret via -* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is -* supplied. This codec deliberately ships only the signed mode and a single -* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and -* an encrypted mode are intentionally out of scope for the initial release. -*/ -function createRequestStateCodec(options) { - const subtle = globalThis.crypto?.subtle; - if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); - const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); - if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); - const ttlSeconds = options.ttlSeconds ?? 600; - if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); - const bind = options.bind; - let cryptoKey; - const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { - name: "HMAC", - hash: "SHA-256" - }, false, ["sign", "verify"]); - const utf8 = new TextEncoder(); - const BIND_LABEL = "mcp.requestState.bind:"; - const bindTag = async (value) => { - return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); - }; - return { - async mint(payload, ctx) { - const envelope = { - p: payload, - exp: Math.floor(Date.now() / 1e3) + ttlSeconds - }; - if (bind !== void 0) { - if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); - envelope.b = await bindTag(bind(ctx)); - } - const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); - return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; - }, - async verify(state, ctx) { - const dot = state.lastIndexOf("."); - if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); - const body = state.slice(3, dot); - let macBytes; - try { - macBytes = base64UrlToBytes(state.slice(dot + 1)); - } catch { - throw new Error("malformed"); - } - if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); - let envelope; - try { - envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); - } catch { - throw new Error("malformed"); - } - if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); - if (bind !== void 0) { - const expected = await bindTag(bind(ctx)); - if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); - } else if (envelope.b !== void 0) throw new Error("bind"); - return envelope.p; - } - }; -} - -//#endregion -//#region src/fromJsonSchema.ts -let _defaultValidator; -function dist_fromJsonSchema(schema, validator) { - return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); -} - -//#endregion - -//# sourceMappingURL=index.mjs.map -const mcpApps = Object.freeze([]); - -/* export default */ const mcp_status_073c1634_0 = (mcpApps); - -// Generated by agent-bundle. Do not edit. -const meta_name = "mcp-app-example"; -const packageName = "@agent-bundle-example/mcp-app"; -const packageVersion = undefined; -const meta_version = "1.0.0"; -const meta_meta = Object.freeze({ - name: meta_name, - packageName: packageName, - packageVersion: packageVersion, - version: meta_version -}); -/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - - - - -const app = mcp_status_073c1634_0["0"]; -if (app === undefined) throw new Error('Expected the status MCP App.'); -const serviceCatalog = Object.freeze({ - compiler: healthyCompilerStatus, - 'payments-api': Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'P95 latency', - status: 'failing' - }) - ]), - service: 'payments-api', - status: 'degraded', - summary: 'Payment latency is above the release threshold.' - }) -}); -const createStatusServer = ()=>{ - // The compiler stamps this project's identity into `agent-bundle/meta`, so - // the wire identity cannot drift from the config or package.json. - const server = new mcp_DXXb3Vv3_McpServer({ - name: meta_name, - version: (/* inlined export .version */"1.0.0") - }); - server.registerResource(app.name, app.resourceUri, { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - mimeType: app.mimeType - }, async (uri)=>({ - contents: [ - { - mimeType: app.mimeType, - text: app.html, - uri: uri.href - } - ] - })); - server.registerTool('show-status', { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - description: 'Show the health of one example service.', - inputSchema: schemas_object({ - service: schemas_enum([ - 'compiler', - 'payments-api' - ]) - }) - }, async ({ service })=>{ - const result = serviceCatalog[service]; - return { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - content: [ - { - text: result.summary, - type: 'text' - } - ], - structuredContent: result - }; - }); - return server; -}; -/** - * Default-exported server factory: `agent-bundle build` detects it and wraps - * this entry in the framework stdio lifecycle shell (console-to-stderr guard, - * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). - */ /* export default */ const mcp_status = (createStatusServer); - - - - - -//#region src/server/stdio.ts -/** -* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. -* -* This transport is only available in Node.js environments. -* -* @example -* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* const transport = new StdioServerTransport(); -* await server.connect(transport); -* ``` -*/ -var stdio_StdioServerTransport = class { - _readBuffer; - _started = false; - _closed = false; - constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); - } - onclose; - onerror; - onmessage; - _ondata = (chunk) => { - try { - this._readBuffer.append(chunk); - this.processReadBuffer(); - } catch (error) { - this.onerror?.(error); - this.close().catch(() => {}); - } - }; - _onerror = (error) => { - this.onerror?.(error); - }; - _onstdouterror = (error) => { - this.onerror?.(error); - this.close().catch(() => {}); - }; - /** - * Starts listening for messages on `stdin`. - */ - async start() { - if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); - this._stdout.on("error", this._onstdouterror); - } - processReadBuffer() { - while (true) try { - const message = this._readBuffer.readMessage(); - if (message === null) break; - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - this._stdout.off("error", this._onstdouterror); - if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); - return new Promise((resolve, reject) => { - const json = serializeMessage(message); - let settled = false; - const onError = (error) => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - reject(error); - }; - const onDrain = () => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - resolve(); - }; - this._stdout.once("error", onError); - if (this._stdout.write(json)) { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - resolve(); - } else if (!settled) this._stdout.once("drain", onDrain); - }); - } -}; - -//#endregion -//#region src/server/serveStdio.ts -/** -* How long the probe-discard path waits for the probe instance to answer the -* requests it was delivered before closing it. The wait normally settles as -* soon as the DiscoverResult is handed to the wire (or immediately, when a -* delivered cancellation already settled the probe); the bound is a backstop -* so no edge can ever hold the connection's inbound pump indefinitely behind -* the discard. -*/ -const DISCARD_ANSWER_TIMEOUT_MS = 3e3; -/** -* The transport a pinned instance is connected to: a thin channel that writes -* through to the entry-owned wire transport and receives the messages the -* entry forwards. The wire transport itself is never handed to an instance — -* that is what lets the entry discard an optimistic probe instance (close the -* channel) without tearing down the connection. -*/ -var StdioConnectionChannel = class { - onclose; - onerror; - onmessage; - _closed = false; - /** Request ids the entry delivered to the instance that the instance has not yet answered. */ - _pendingRequests = /* @__PURE__ */ new Set(); - _drainWaiters = []; - constructor(_wire, _onInstanceClose, _outboundIntercept) { - this._wire = _wire; - this._onInstanceClose = _onInstanceClose; - this._outboundIntercept = _outboundIntercept; - } - async start() {} - async send(message, options) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - const { id } = message; - if (id !== void 0) this._settle(id); - } - if (this._closed) return; - if (this._outboundIntercept?.(message) === "handled") return; - return this._wire.send(message, options); - } - setProtocolVersion = (version) => { - this._wire.setProtocolVersion?.(version); - }; - /** Forwards one inbound message to the connected instance. */ - deliver(message, extra) { - if (this._closed) return; - if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); - else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0) this._settle(cancelledId); - } - this.onmessage?.(message, extra); - } - /** - * Resolves once every request delivered to the instance has been answered - * through {@linkcode send}, settled by a delivered cancellation, or the - * channel has been closed and nothing further can be answered. The wait is - * bounded by `timeoutMs` as a backstop so no edge can hold the caller - * indefinitely; resolves `false` only when the bound elapsed with requests - * still unanswered. Used by the probe-discard path so a probe request the - * entry accepted is never silently dropped. - */ - async whenRequestsAnswered(timeoutMs) { - if (this._closed || this._pendingRequests.size === 0) return true; - return await new Promise((resolve) => { - const waiter = () => { - clearTimeout(timer); - resolve(true); - }; - const timer = setTimeout(() => { - this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); - resolve(false); - }, timeoutMs); - this._drainWaiters.push(waiter); - }); - } - async close() { - if (this._closed) return; - this._closed = true; - this._pendingRequests.clear(); - this._releaseDrainWaiters(); - try { - this._onInstanceClose(); - } finally { - this.onclose?.(); - } - } - _settle(id) { - this._pendingRequests.delete(id); - if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); - } - _releaseDrainWaiters() { - const waiters = this._drainWaiters; - this._drainWaiters = []; - for (const waiter of waiters) waiter(); - } -}; -/** -* Classifies one message of the opening exchange with the same body-primary -* rules the HTTP entry applies per request: `initialize` is the legacy -* handshake unless it carries a valid modern envelope claim; a present claim -* is validated (never silently ignored); a claim-less message is 2025-era -* traffic. There is no header layer on stdio, so the body is the only signal. -*/ -function classifyOpeningMessage(message) { - const params = message.params; - if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { - const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (!hasEnvelopeClaim(params)) return { - kind: "legacy", - reason: "no-claim" - }; - const meta = requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return { - kind: "invalid-envelope", - issue: firstIssue - }; - const claimedVersion = envelopeClaimVersion(params); - if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { - kind: "unsupported-revision", - requested: claimedVersion ?? "unknown" - }; - return { - kind: "modern", - revision: claimedVersion, - classification: { - era: "modern", - revision: claimedVersion - } - }; -} -/** -* Serves MCP over stdio from a server factory, owning the era decision for -* the connection: the opening exchange selects the era, ONE instance from the -* factory is pinned for the connection lifetime, and everything after passes -* straight through to it. See the module documentation for the opening rules. -* -* ```ts -* import { serveStdio } from '@modelcontextprotocol/server/stdio'; -* -* serveStdio(() => { -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); -* // register tools/resources/prompts once — the same factory serves both eras -* return server; -* }); -* ``` -*/ -function serveStdio(factory, options = {}) { - const legacyMode = options.legacy ?? "serve"; - const wire = options.transport ?? new stdio_StdioServerTransport(); - let state = { phase: "opening" }; - /** Channel currently being discarded (its close must not tear the connection down). */ - let discarding; - let closing = false; - /** - * Whether the connection has been torn down (`handle.close()` or the wire - * closing). The opening arms re-check this after every await: a close can - * race factory construction, and the continuation must neither resurrect - * the connection state nor keep a late-resolved instance around. - */ - const isTornDown = () => closing || state.phase === "closed"; - const reportError = (error) => { - try { - options.onerror?.(error); - } catch {} - }; - const writeErrorResponse = (id, code, message, data) => wire.send({ - jsonrpc: "2.0", - id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }).catch((error) => reportError(stdio_toError(error))); - /** - * Entry-handled `subscriptions/listen` for this connection: holds the - * active subscriptions, serves inbound listen / cancelled-of-listen - * before the pinned instance is consulted, and rewrites the instance's - * outbound change notifications onto the active subscriptions. Only - * consulted on a modern-pinned connection — on a legacy connection - * change notifications pass straight through (the 2025 unsolicited - * delivery model is unchanged). - */ - const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); - /** Outbound intercept installed on a modern instance's channel. */ - const modernOutboundIntercept = (message) => { - if (!isJSONRPCNotification(message)) return void 0; - const routed = listenRouter.routeOutbound(message); - if (routed === "passthrough") return void 0; - for (const stamped of routed) wire.send({ - jsonrpc: "2.0", - ...stamped - }).catch((error) => reportError(stdio_toError(error))); - return "handled"; - }; - /** - * Entry-handled inbound listen routing for a modern-pinned connection. - * Returns `true` when the message was served at the entry and must NOT - * be delivered to the pinned instance. - */ - const tryServeListen = async (message) => { - if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { - const meta = requestMetaOf(message.params); - const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { - key: "_meta", - problem: "the per-request envelope is required on protocol revision 2026-07-28" - }; - const claimedVersion = envelopeClaimVersion(message.params); - let reply; - if (issue !== void 0) reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` - } - }; - else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedVersion ?? "unknown" - }); - reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: error.code, - message: error.message, - data: error.data - } - }; - } else reply = listenRouter.serve(message); - await wire.send("error" in reply ? reply : { - jsonrpc: "2.0", - method: reply.method, - params: reply.params - }).catch((error) => reportError(stdio_toError(error))); - return true; - } - if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; - } - return false; - }; - /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ - const answerLegacyRejection = (request, reason, requestedVersion) => { - const rejection = modernOnlyStrictRejection({ - kind: "legacy", - reason, - ...requestedVersion !== void 0 && { requestedVersion } - }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (rejection === void 0) return Promise.resolve(); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); - return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); - }; - const onInstanceClosed = (channel) => { - if (closing || channel === discarding) return; - closeAll(); - }; - const connectInstance = async (era, revision) => { - const product = await factory({ era }); - const server = product instanceof McpServer ? product.server : product; - if (era === "modern") { - setNegotiatedProtocolVersion(server, revision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); - } - const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); - await product.connect(channel); - return { - product, - channel - }; - }; - /** Closes an instance whose factory resolved only after the connection was torn down. */ - const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); - const discardProbeInstance = async (instance) => { - discarding = instance.channel; - try { - if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); - await instance.product.close(); - } catch (error) { - reportError(stdio_toError(error)); - } finally { - discarding = void 0; - } - }; - const processMessage = async (message) => { - if (state.phase === "closed") return; - if (state.phase === "pinned") { - if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { - await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); - return; - } - if (state.era === "modern" && await tryServeListen(message)) return; - state.instance.channel.deliver(message); - return; - } - if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { - reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); - return; - } - const opening = classifyOpeningMessage(message); - switch (opening.kind) { - case "invalid-envelope": { - const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); - else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); - return; - } - case "unsupported-revision": - if (isJSONRPCRequest(message)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: opening.requested - }); - reportError(error); - await writeErrorResponse(message.id, error.code, error.message, error.data); - } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); - return; - case "modern": - if (isJSONRPCRequest(message) && message.method === "server/discover") { - if (state.phase === "probe") { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "probe", - instance - }; - instance.channel.deliver(message, { classification: opening.classification }); - return; - } - if (state.phase === "probe") { - if (isJSONRPCNotification(message)) { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - state = { - phase: "pinned", - era: "modern", - instance: state.instance - }; - } else { - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "modern", - instance - }; - } - if (await tryServeListen(message)) return; - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - case "legacy": { - if (legacyMode === "reject") { - if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); - return; - } - if (state.phase === "probe") { - await discardProbeInstance(state.instance); - if (isTornDown()) return; - state = { phase: "opening" }; - } - const instance = await connectInstance("legacy"); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "legacy", - instance - }; - state.instance.channel.deliver(message); - return; - } - } - }; - const queue = []; - let pumping = false; - const pump = async () => { - if (pumping) return; - pumping = true; - try { - while (queue.length > 0) { - const message = queue.shift(); - try { - await processMessage(message); - } catch (error) { - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); - reportError(stdio_toError(error)); - } - } - } finally { - pumping = false; - } - }; - const closeAll = async () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); - if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - await wire.close().catch((error) => reportError(stdio_toError(error))); - }; - wire.onmessage = (message) => { - queue.push(message); - pump(); - }; - wire.onerror = (error) => { - reportError(error); - if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); - }; - wire.onclose = () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - }; - const started = wire.start().catch((error) => { - reportError(stdio_toError(error)); - throw error; - }); - started.catch(() => {}); - return { close: async () => { - await started.catch(() => {}); - await closeAll(); - } }; -} -function stdio_toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} - -//#endregion - -//# sourceMappingURL=stdio.mjs.map -const defaultHeartbeatIntervalMs = 300000; -const defaultActivityThrottleMs = 60000; -const defaultShutdownTimeoutMs = 5000; -const defaultHeartbeatName = 'agent-bundle'; -const redirectConsoleToStderr = ()=>{ - const originalStdoutWrite = process.stdout.write.bind(process.stdout); - const stderrConsole = new console.Console({ - stderr: process.stderr, - stdout: process.stderr - }); - const methods = [ - 'debug', - 'dir', - 'error', - 'info', - 'log', - 'trace', - 'warn' - ]; - for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); - process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); - return Object.freeze({ - restoreProtocolStdout: ()=>{ - process.stdout.write = originalStdoutWrite; - } - }); -}; -const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ - const startedAt = Date.now(); - let lastActivityAt = startedAt; - let lastActivityLogAt = 0; - const log = (reason)=>{ - const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); - const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); - writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); - }; - const timer = setInterval(()=>log('interval'), intervalMs); - timer.unref?.(); - return Object.freeze({ - log, - noteActivity: ()=>{ - lastActivityAt = Date.now(); - if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { - lastActivityLogAt = lastActivityAt; - log('activity'); - } - }, - stop: ()=>clearInterval(timer) - }); -}; -const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ - const heartbeat = createHeartbeat({ - ...void 0 === activityThrottleMs ? {} : { - activityThrottleMs - }, - ...void 0 === heartbeatIntervalMs ? {} : { - intervalMs: heartbeatIntervalMs - }, - ...void 0 === serverName ? {} : { - name: serverName - }, - writeLine: heartbeatEnabled ? writeLine : ()=>void 0 - }); - const keepalive = setInterval(()=>void 0, 60000); - keepalive.unref?.(); - let shuttingDown = false; - const shutdown = async (exitCode = 0)=>{ - if (shuttingDown) return; - shuttingDown = true; - signals.off('SIGINT', handleSigint); - signals.off('SIGTERM', handleSigterm); - stdin.off?.('end', handleStdinEnd); - clearInterval(keepalive); - heartbeat.stop(); - await Promise.race([ - Promise.allSettled([ - Promise.resolve().then(()=>transport.close()), - Promise.resolve().then(()=>server.close()) - ]), - new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) - ]); - exit(exitCode); - }; - const handleSigint = ()=>{ - shutdown(130); - }; - const handleSigterm = ()=>{ - shutdown(143); - }; - const handleStdinEnd = ()=>{ - shutdown(0); - }; - signals.on('SIGINT', handleSigint); - signals.on('SIGTERM', handleSigterm); - stdin.once?.('end', handleStdinEnd); - transport.onclose = ()=>{ - shutdown(0); - }; - await server.connect(transport); - const originalOnMessage = transport.onmessage; - transport.onmessage = (message, extra)=>{ - heartbeat.noteActivity(); - originalOnMessage?.(message, extra); - }; - return Object.freeze({ - heartbeat, - shutdown - }); -}; -const runGeneratedStdioMcpEntry = async (options)=>{ - const guard = redirectConsoleToStderr(); - const entry = await options.loadEntry(); - const factory = entry.default; - if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); - const server = await factory(); - const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); - guard.restoreProtocolStdout(); - const transport = new StdioServerTransport(); - return runStdioServer({ - ...options.lifecycle, - server, - serverName: options.serverName, - transport: transport - }); -}; - - - -await runGeneratedStdioMcpEntry({ - loadEntry: ()=>Promise.resolve(status_namespaceObject), - serverName: "status" -}); - -export {}; diff --git a/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs deleted file mode 100644 index a6f274bf6..000000000 --- a/examples/mcp-app/artifact/codex/scripts/check-service-fixture.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - -const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); -/** - * `agent-bundle build` detects the `main` export and generates the process - * envelope (argv, awaiting, numeric-return exit-code adoption) around it. - */ const main = async ()=>{ - try { - const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); - if (!isHealthyCompilerFixture(fixture)) { - throw new Error('compiler fixture must contain the exact healthy compiler status'); - } - process.stdout.write('Compiler fixture is healthy.\n'); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const check_service_fixture_entry_main = main; -if (typeof check_service_fixture_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/mcp-app/src/scripts/check-service-fixture.ts"); -} -const code = await check_service_fixture_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md deleted file mode 100644 index 8f91a79d7..000000000 --- a/examples/mcp-app/artifact/codex/skills/service-readiness/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: service-readiness -description: Reviews service health evidence and records an auditable readiness decision. ---- -# Service readiness - -## When to use - -Use this Skill when a release, incident decision, or service handoff needs a -clear health verdict backed by named checks and current evidence. - -## Required resources - -- Apply [the service status policy](references/status-policy.md) before - classifying a healthy, degraded, or blocked result. -- Deliver the decision with [the readiness report](assets/readiness-report.md). - -## Workflow - -1. Identify the service and collect its current summary and every labelled - check. Record the command, time, result, and evidence source. -2. Classify any failing check with the status policy. A degraded service is not - release-ready until its failing check has an approved mitigation. -3. State the readiness verdict only after confirming availability and the - service-specific release threshold. -4. Complete the report with the status, checks, evidence, owner, and next - action. Do not omit a failing check from the final decision. - -## Final report requirements - -State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the -service summary; list each labelled check and its status; identify the owner -and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md deleted file mode 100644 index 3da5d52ea..000000000 --- a/examples/mcp-app/artifact/codex/skills/service-readiness/assets/readiness-report.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service readiness report - -## Verdict - -State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. - -## Evidence - -Record the collection time, command or artifact, service summary, and source. - -## Checks - -List every labelled check with its observed status and release threshold. - -## Findings and mitigation - -For each non-passing check, record the impact, owner, mitigation, due date, -and the evidence required to clear it. - -## Next action - -Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md deleted file mode 100644 index 7e5766172..000000000 --- a/examples/mcp-app/artifact/codex/skills/service-readiness/references/status-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service status policy - -## Evidence standard - -Readiness evidence must identify the service, collection time, check label, -observed status, and source command or artifact. Missing or stale evidence is -not a passing check. - -## Status classification - -- **Healthy**: every required release check is passing. -- **Degraded**: availability remains sufficient, but a release threshold such - as P95 latency is failing. Record an owner and mitigation before release. -- **Blocked**: availability or a critical safety check is failing. Do not - release until new passing evidence is collected. -- **Needs evidence**: the service or any required check cannot be verified. - -## Release decision - -Issue `ready` only for a healthy service with current evidence. A degraded -service needs an explicit mitigation decision; a blocked service cannot pass; -and missing evidence requires a new check rather than an assumption. diff --git a/examples/mcp-app/artifact/portable/INSTALL.md b/examples/mcp-app/artifact/portable/INSTALL.md deleted file mode 100644 index 5ba00d88e..000000000 --- a/examples/mcp-app/artifact/portable/INSTALL.md +++ /dev/null @@ -1,19 +0,0 @@ -# Install mcp-app-example - -A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Portable Agent Plugin - -Portable is a distribution profile, not a host runtime with one universal install location. -This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). -Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run -`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT -are also native clients. The bundled installer provides the Cursor local copy: - -```sh -node ./install.mjs -``` diff --git a/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json b/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json deleted file mode 100644 index a765aa4b5..000000000 --- a/examples/mcp-app/artifact/portable/assets/evals/fixtures/status/result.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "service": "compiler", - "status": "healthy", - "summary": "Compiler service is ready for release.", - "checks": [ - { "label": "Availability", "status": "passing" }, - { "label": "Build queue", "status": "passing" } - ] -} diff --git a/examples/mcp-app/artifact/portable/install.mjs b/examples/mcp-app/artifact/portable/install.mjs deleted file mode 100644 index 1d942a81a..000000000 --- a/examples/mcp-app/artifact/portable/install.mjs +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node -import { createHash } from 'node:crypto'; -import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const pluginName = "mcp-app-example"; -const pluginVersion = "1.0.0"; -const source = resolve(fileURLToPath(new URL('.', import.meta.url))); -const cursorRoot = join(homedir(), '.cursor'); -const installRoot = join(cursorRoot, 'plugins', 'local'); -const destination = join(installRoot, pluginName); - -const exists = async (path) => { - try { await lstat(path); return true; } - catch (error) { if (error?.code === 'ENOENT') return false; throw error; } -}; - -const treeHash = async (root, prefix = '') => { - const rootMetadata = await lstat(root); - if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { - throw new Error('Refusing unsupported filesystem entry ".".'); - } - const hash = createHash('sha256'); - const visit = async (relative) => { - const absolute = join(root, relative); - const metadata = await lstat(absolute); - if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { - throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); - } - if (metadata.isDirectory()) { - for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); - return; - } - hash.update(relative.replaceAll('\\', '/')); - hash.update('\0'); - hash.update(await readFile(absolute)); - hash.update('\0'); - }; - for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); - return hash.digest('hex'); -}; - -const installedVersion = async () => { - for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { - try { - const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); - if (typeof value.version === 'string') return value.version; - } catch (error) { if (error?.code !== 'ENOENT') throw error; } - } - return undefined; -}; - -if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { - throw new Error(`Cursor is not installed in ${cursorRoot}.`); -} -await mkdir(installRoot, { recursive: true }); -if (await exists(destination)) { - const currentVersion = await installedVersion(); - if (currentVersion !== undefined && currentVersion !== pluginVersion) { - throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); - } - if (source === destination || await treeHash(source) === await treeHash(destination)) { - console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); - process.exit(0); - } - throw new Error(`Refusing content collision at ${destination}.`); -} - -const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); -const stage = join(stageParent, 'bundle'); -try { - await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); - await treeHash(stage); - await rename(stage, destination); - console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); -} finally { - await rm(stageParent, { force: true, recursive: true }); -} diff --git a/examples/mcp-app/artifact/portable/mcp-apps/status.html b/examples/mcp-app/artifact/portable/mcp-apps/status.html deleted file mode 100644 index d1ca000c0..000000000 --- a/examples/mcp-app/artifact/portable/mcp-apps/status.html +++ /dev/null @@ -1,154 +0,0 @@ - - - - - - Service status - - - -
      -
      MCP App example
      -

      No service selected

      -
      unknown
      -

      Invoke the readiness tool to inspect a service.

      -
        - - - - -

        -
        - - diff --git a/examples/mcp-app/artifact/portable/mcp.json b/examples/mcp-app/artifact/portable/mcp.json deleted file mode 100644 index ac9282f22..000000000 --- a/examples/mcp-app/artifact/portable/mcp.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/mcp.schema.json","mcpServers":{"status":{"args":["mcp/mcp-status-073c1634.mjs"],"command":"node","cwd":"${PLUGIN_ROOT}","env":{"AGENT_BUNDLE_PLUGIN_ROOT":"${PLUGIN_ROOT}"},"type":"stdio"}}} diff --git a/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs b/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs deleted file mode 100644 index 6b4d8ca65..000000000 --- a/examples/mcp-app/artifact/portable/mcp/mcp-status-073c1634.mjs +++ /dev/null @@ -1,30768 +0,0 @@ -import node_process from "node:process"; - -// The require scope -var __webpack_require__ = {}; - -// webpack/runtime/define_property_getters -(() => { -__webpack_require__.d = (exports, getters, values) => { - var define = (defs, kind) => { - for(var key in defs) { - if(__webpack_require__.o(defs, key) && !__webpack_require__.o(exports, key)) { - Object.defineProperty(exports, key, { enumerable: true, [kind]: defs[key] }); - } - } - }; - define(getters, "get"); - define(values, "value"); -}; -})(); -// webpack/runtime/has_own_property -(() => { -__webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -})(); -// webpack/runtime/make_namespace_object -(() => { -// define __esModule on exports -__webpack_require__.r = (exports) => { - if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { - Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); - } - Object.defineProperty(exports, '__esModule', { value: true }); -}; -})(); - -// NAMESPACE OBJECT: ./src/mcp/status.ts -var status_namespaceObject = {}; -__webpack_require__.r(status_namespaceObject); -__webpack_require__.d(status_namespaceObject, { - createStatusServer: () => (createStatusServer), - "default": () => (mcp_status) }); - - -// NAMESPACE OBJECT: ../../node_modules/.pnpm/@modelcontextprotocol+server@2.0.0/node_modules/@modelcontextprotocol/server/dist/stdio.mjs -var stdio_namespaceObject = {}; -__webpack_require__.r(stdio_namespaceObject); -__webpack_require__.d(stdio_namespaceObject, { - StdioServerTransport: () => (stdio_StdioServerTransport) }); - - -//#region rolldown:runtime -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports); -var __exportAll = (all, symbols) => { - let target = {}; - for (var name in all) { - __defProp(target, name, { - get: all[name], - enumerable: true - }); - } - if (symbols) { - __defProp(target, Symbol.toStringTag, { value: "Module" }); - } - return target; -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) { - key = keys[i]; - if (!__hasOwnProp.call(to, key) && key !== except) { - __defProp(to, key, { - get: ((k) => from[k]).bind(null, key), - enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable - }); - } - } - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { - value: mod, - enumerable: true -}) : target, mod)); - -//#endregion - -//#region ../core-internal/src/validators/dialects.ts -/** -* Canonical `$schema` URIs per supported dialect (http + https variants, trailing-`#` stripped). -*/ -const DRAFT_2020_12_URIS = new Set(["https://json-schema.org/draft/2020-12/schema", "http://json-schema.org/draft/2020-12/schema"]); -const DRAFT_2019_09_URIS = new Set(["https://json-schema.org/draft/2019-09/schema", "http://json-schema.org/draft/2019-09/schema"]); -const DRAFT_07_URIS = new Set(["https://json-schema.org/draft-07/schema", "http://json-schema.org/draft-07/schema"]); -const DRAFT_06_URIS = new Set(["https://json-schema.org/draft-06/schema", "http://json-schema.org/draft-06/schema"]); -/** -* Whether a `$schema` value declares the 2019-09 dialect — the only supported dialect with -* `$recursiveRef`/`$recursiveAnchor`. Non-throwing (unlike {@linkcode declaredDialect}) so -* wire-layer callers can consult it for documents whose dialect may be unsupported. -*/ -function declares2019Dialect($schema) { - return typeof $schema === "string" && DRAFT_2019_09_URIS.has($schema.replace(/#$/, "")); -} -/** -* Classify a schema's declared `$schema` dialect. No `$schema` (or a non-string one) means -* 2020-12. Any other dialect throws a plain `Error` with a clear message rather than letting the -* engine crash on an opaque internal error or silently mis-validate; `remedy` names the calling -* provider's escape hatch in that message. -*/ -function declaredDialect(schema, remedy) { - if (!("$schema" in schema) || typeof schema.$schema !== "string") return "2020-12"; - const declared = schema.$schema.replace(/#$/, ""); - if (DRAFT_2020_12_URIS.has(declared)) return "2020-12"; - if (DRAFT_2019_09_URIS.has(declared)) return "2019-09"; - if (DRAFT_07_URIS.has(declared) || DRAFT_06_URIS.has(declared)) return "draft-7"; - throw new Error(`JSON Schema declares an unsupported dialect ("$schema": "${schema.$schema.slice(0, 200)}"). The default validator supports JSON Schema 2020-12, 2019-09, draft-07, and draft-06; ${remedy}`); -} - -//#endregion - -//# sourceMappingURL=dialects-DoSzNhcb.mjs.map - -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function toZod() { - return (schema) => schema; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function util_cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const ratio = val / step; - const roundedRatio = Math.round(ratio); - // `val` and `step` each round to a double before the division rounds again, so a true decimal multiple's quotient can sit up to 1.5 of these scaled epsilons from the integer. A 1x tolerance therefore rejected 2.03 as a multiple of 0.07; 4x covers the worst case with margin. - const tolerance = 4 * Number.EPSILON * Math.max(Math.abs(ratio), 1); - if (Math.abs(ratio - roundedRatio) < tolerance) - return 0; - return ratio - roundedRatio; -} -const EVALUATING = /* @__PURE__*/ Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - // Circular reference detected, return undefined to break the cycle - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function util_esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function util_isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const util_allowsEval = /* @__PURE__*/ util_cached(() => { - // Skip the probe under `jitless`: strict CSPs report the caught `new Function` as a `securitypolicyviolation` even though the throw is swallowed. - if (globalConfig.jitless) { - return false; - } - // @ts-ignore - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (util_isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - // modified prototype - const prot = ctor.prototype; - if (util_isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - if (o instanceof Map) - return new Map(o); - if (o instanceof Set) - return new Set(o); - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - // @ts-ignore - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = /* @__PURE__*/ new Set(["string", "number", "symbol"]); -const primitiveTypes = /* @__PURE__*/ (/* unused pure expression or super */ null && (new Set([ - "string", - "number", - "bigint", - "boolean", - "symbol", - "undefined", -]))); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin !== undefined && shape[k]._zod.optout === "optional"; - }); -} -// Wrapped in a `@__PURE__` IIFE: esbuild never tree-shakes a top-level initializer that contains a member access on `Number`, so the bare object literal survived into every bundle. -const NUMBER_FORMAT_RANGES = /*@__PURE__*/ (() => ({ - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}))(); -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".pick() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - // `for...in` skips symbols, so a symbol in the mask would select nothing - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - assignProp(newShape, key, currDef.shape[key]); - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(".omit() cannot be used on object schemas containing refinements"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(currDef.shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - // Only throw if new shape overlaps with existing shape. Use getOwnPropertyDescriptor to check key existence without accessing values - const existingShape = schema._zod.def.shape; - for (const key of Reflect.ownKeys(shape)) { - if (Object.getOwnPropertyDescriptor(existingShape, key) !== undefined) { - throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead."); - } - } - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - }); - return clone(schema, def); -} -function merge(a, b) { - if (!b?._zod?.def) { - throw new Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`."); - } - if (a._zod.def.checks?.length) { - throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead."); - } - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: b._zod.def.checks ?? [], - }); - return clone(a, def); -} -function partial(Class, schema, mask, name = "partial") { - const currDef = schema._zod.def; - const checks = currDef.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error(`.${name}() cannot be used on object schemas containing refinements`); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(oldShape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - // the spread copies symbol keys; `for...in` would not reach them - for (const key of Reflect.ownKeys(oldShape)) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function util_required(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key of Reflect.ownKeys(mask)) { - if (!Object.prototype.hasOwnProperty.call(shape, key)) { - throw new Error(`Unrecognized key: "${String(key)}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key of Reflect.ownKeys(oldShape)) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - }); - return clone(schema, def); -} -// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -// Checks for explicit abort (continue === false), as opposed to implicit abort (continue === undefined). Used to respect `abort: true` in .refine() even for checks that have a `when` function. -function explicitlyAborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue === false) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -/* A check holds no link back to the schema it is attached to — the same check instance is shared by every clone of that schema — so the owner is stamped onto the issues a check just raised, at the only point where both are in scope. Runs on the failure path only; `start` is the issue count from before the check ran. */ -function attachSchema(issues, start, inst) { - var _a; - for (let i = start; i < issues.length; i++) { - (_a = issues[i]).schema ?? (_a.schema = inst); - } -} -function finalizeIssue(iss, ctx, config) { - var _a; - // A schema that raised an issue itself owns it outright, and outranks any stamp an enclosing check left in `attachSchema`. String formats and z.custom() are schema and check at once, so when they act as a check they defer to that stamp instead. - const traits = iss.inst?._zod?.traits; - if (traits?.has("$ZodType")) { - if (traits.has("$ZodCheck")) - (_a = iss).schema ?? (_a.schema = iss.inst); - else - iss.schema = iss.inst; - } - // Decreasing specificity, first map to return a message wins. `inst` is whatever raised the issue, so a check's own map outranks the owning schema's. - const schemaError = iss.schema !== iss.inst ? iss.schema?._zod.def?.error : undefined; - const message = iss.message - ? iss.message - : (unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(schemaError?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"); - const { inst: _inst, schema: _schema, continue: _continue, input: _input, ...rest } = iss; - rest.path ?? (rest.path = []); - rest.message = message; - if (ctx?.reportInput) { - rest.input = _input; - } - return rest; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - // @ts-ignore - if (input instanceof File) - return "file"; - return "unknown"; -} -const highSurrogate = /[\uD800-\uDBFF]/; -// Code points in `str`: a surrogate pair counts once, a lone surrogate as itself. Hand-rolled because the string iterator allocates and runs ~250x slower on this path; the regex probe exits ~50x quicker for a string with no astral characters. -function codePointLength(str) { - const units = str.length; - if (!highSurrogate.test(str)) - return units; - let count = units; - for (let i = 0; i < units - 1; i++) { - if ((str.charCodeAt(i) & 0xfc00) === 0xd800 && (str.charCodeAt(i + 1) & 0xfc00) === 0xdc00) { - count--; - i++; - } - } - return count; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function parsedType(data) { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "nan" : "number"; - } - case "object": { - if (data === null) { - return "null"; - } - if (Array.isArray(data)) { - return "array"; - } - const obj = data; - if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) { - return obj.constructor.name; - } - } - } - return t; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// Codec utility functions -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -// instanceof -class util_Class { - constructor(..._args) { } -} -////////// PROTOTYPE INSTALLERS ////////// -// -// Members live on the prototype and materialize per instance on first read, which keeps own-property count under the step where V8 stops using inline slots. Changing anything here means re-measuring runtime, memory and bundle size together — see "The three axes" in AGENTS.md. -/** - * Installs a trait's members on its prototype. Each value builds that member for the instance on first read; the built value shadows the accessor as an own property, so a detached `const { parse } = schema` keeps working. - * - * Call this from a `proto` initializer, which runs once per prototype — never per instance. - */ -function util_members(proto, table) { - for (const key in table) { - const desc = Object.getOwnPropertyDescriptor(table, key); - // a getter installs as written, so it stays live: `description` reads through to the registry on every access. not enumerable: an object literal's is, and a prototype member never was - if (desc.get) - Object.defineProperty(proto, key, { ...desc, enumerable: false }); - // a method materializes bound on first read, which is what keeps a detached member working: `const opt = schema.optional; opt()` - else - defineBound(proto, key, desc.value); - } -} -/** Shadows a prototype member with an own value, so a getter that builds from the instance runs once. */ -function util_own(inst, key, value, enumerable = true) { - Object.defineProperty(inst, key, { configurable: true, writable: true, enumerable, value }); - return value; -} -/** Like {@link own}, for a member that was never an own data property and has to stay out of `Object.keys`. */ -function hide(inst, key, value) { - return util_own(inst, key, value, false); -} -function defineBound(proto, key, fn) { - Object.defineProperty(proto, key, { - configurable: true, - get() { - // vitest's spyOn calls a prototype getter bare to find the function it wraps, so a nullish receiver answers the raw method - return this == null ? fn : util_own(this, key, fn.bind(this)); - }, - set(value) { - util_own(this, key, value); - }, - }); -} -/** Returns the prototype to install on, or `undefined` if this group is already installed on it. */ -function claim(inst, sentinel) { - const proto = Object.getPrototypeOf(inst); - // Runs on every construction, so `in` rather than the costlier `hasOwnProperty.call`. Sentinels are keys the group itself defines. - return sentinel in proto ? undefined : proto; -} -// The internals whose init chain is installing. A second call for the same one is a derived constructor overriding its base, so it must not construct another schema in between or the override is dropped. -let installing; -// Set while a getter is running, so a value that resolved through a recursion break is not memoized. One shared descriptor shadows the key for the duration, which costs no per-key allocation. -let broke = false; -const breaker = { - configurable: true, - get() { - broke = true; - return undefined; - }, -}; -/** - * Installs a lazily-derived internal on the `_zod` prototype of `inst`'s - * constructor, computed from the internals object itself and cached there on - * first read. One accessor per constructor rather than one per instance. - */ -function defineLazyInternal(inst, key, compute) { - const proto = Object.getPrototypeOf(inst._zod); - if (key in proto && installing !== inst._zod) { - // A repeat construction: everything is installed already. Cleared here so the reference is not held past the first construction of every type. - installing = undefined; - return; - } - installing = inst._zod; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing so a re-entrant read from a recursive schema resolves to undefined instead of running the getter again. - Object.defineProperty(this, key, breaker); - const outer = broke; - broke = false; - try { - const value = compute(this); - // A result that resolved through a recursion break is recomputed once the graph is complete; everything else memoizes, undefined included. - if (broke) - delete this[key]; - else - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - broke = broke || outer; - return value; - } - catch (err) { - // A compute that threw memoizes nothing, so a later read runs it again and fails the same way. The shadow goes with it, since leaving it installed would answer undefined for every later read. - delete this[key]; - broke = broke || outer; - throw err; - } - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, value }); - }, - }); -} -/** - * Installs `key` on `inst`'s prototype, computed by `make` on first read and cached there as an own - * data property. One accessor per constructor rather than one per instance, because an own accessor - * puts every instance after the first into v8 dictionary mode. The key doubles as the sentinel. - */ -function installLazyProp(inst, key, make, enumerable) { - const proto = claim(inst, key); - if (!proto) - return; - Object.defineProperty(proto, key, { - configurable: true, - get() { - // Shadowed before computing, so a re-entrant read from a self-referential shape resolves to undefined instead of running the getter again. A data property rather than an accessor: an own accessor is the dictionary-mode transition this exists to avoid. - const desc = { configurable: true, writable: true, enumerable, value: undefined }; - Object.defineProperty(this, key, desc); - // a compute that throws leaves the shadow behind, so later reads answer undefined instead of re-throwing; `defineLazy` did the same, and `defineLazyInternal`'s delete-on-catch would cost bytes in every bundle for a case only a throwing user getter reaches - desc.value = make(this); - Object.defineProperty(this, key, desc); - return desc.value; - }, - set(value) { - Object.defineProperty(this, key, { configurable: true, writable: true, enumerable, value }); - }, - }); -} -/** Marks the thunk `_catch` synthesises for a constant catch value. `Function.length` cannot tell that thunk from a user callback — rest and defaulted parameters both report arity 0 — and a user callback reads `ctx.error`, whose issues only finalize correctly against the caller's per-parse error map. Provenance can say what arity cannot. A plain string key rather than `Symbol.for`, whose call at module scope no bundler can prove pure — the same shape that anchored `urlCanParse` into every build. */ -const CONSTANT_CATCH = "~constantCatch"; -/** Wraps a constant catch value in a thunk tagged with {@link CONSTANT_CATCH}. */ -function constantCatch(value) { - const fn = () => value; - fn[CONSTANT_CATCH] = true; - return fn; -} - -var core_a; - -/** A special constant with type `never` */ -const NEVER = /*@__PURE__*/ Object.freeze({ - status: "aborted", -}); -/* Shared descriptor for installing `_zod`; defineProperty reads it - * synchronously, so reusing one object avoids a per-instance allocation. */ -const _zodDesc = { value: undefined, enumerable: false }; -// null where suppressing the capture would be unrecoverable: `parse()` puts the frames back with `captureStackTrace`, so without it the throw would lose its stack. also latched to null once `stackTraceLimit` proves unassignable, which a realm can do at any point by hardening Error -let _E = "captureStackTrace" in Error ? Error : null; -// v8 captures a stack trace inside the Error constructor, which dominates a failed parse; costs only the frames, and parse() restores those. the constructor must RUN: Object.create is cheaper and passes instanceof, but Error.isError and util.types.isNativeError check an internal slot -function newError(Definition) { - const E = _E; - if (E) { - const saved = E.stackTraceLimit; - if (typeof saved === "number") { - try { - E.stackTraceLimit = 0; - } - catch { - _E = null; - return new Definition(); - } - try { - return new Definition(); - } - finally { - E.stackTraceLimit = saved; - } - } - } - return new Definition(); -} -function $constructor(name, initializer, -/** This trait's members, installed once on every prototype that composes it. They cannot be declared in the initializer above: that runs per instance, and the prototype is shared. */ -proto, params) { - // Prototype for this constructor's `_zod` internals. Lazily-derived fields (`values`, `pattern`, `optin`, …) install here once rather than as an accessor on every instance. - const zodProto = {}; - // Assigning the fields in the constructor body is what gives instances in-object slots; building the object literally and reparenting it costs a second allocation and a generic property copy. - function Internals(def) { - this.def = def; - this.constr = _; - this.traits = new Set(); - } - Internals.prototype = zodProto; - const protoMembers = proto; - // One trait's members land on every prototype whose chain composes it, so the answer is per prototype rather than per trait. - const initialized = protoMembers && new WeakSet(); - function init(inst, def) { - if (!inst._zod) { - _zodDesc.value = new Internals(def); - try { - Object.defineProperty(inst, "_zod", _zodDesc); - } - finally { - // Cleared even on throw, so the shared descriptor never leaks one instance's internals into the next. - _zodDesc.value = undefined; - } - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - if (initialized) { - // `super(def)` from a user subclass gives `this` a prototype the subclass owns, and installing there would overwrite whatever the subclass declared. `constr` built the instance, so its prototype is the one below the subclass's that should carry the members. A receiver whose chain never reaches that prototype installs on its own, which for a plain object handed straight to `init` means `Object.prototype` — unchanged from before. - const own = Object.getPrototypeOf(inst); - const ctorProto = inst._zod.constr.prototype; - let up = own; - while (up && up !== ctorProto) - up = Object.getPrototypeOf(up); - const target = up ?? own; - if (!initialized.has(target)) { - initialized.add(target); - util_members(target, protoMembers); - } - } - // support prototype modifications; for-in avoids the array allocation of Object.keys on the (usually empty) prototype - const proto = _.prototype; - for (const k in proto) { - if (!Object.prototype.hasOwnProperty.call(proto, k)) - continue; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - const inst = params?.Parent ? newError(Definition) : this; - init(inst, def); - const deferred = inst._zod.deferred; - if (deferred) { - for (const fn of deferred) { - fn(); - } - // Released: initializers run once, and the list would otherwise be retained for the schema's lifetime. - inst._zod.deferred = undefined; - } - // Global post-processor hook. Internal: installed by `import "zod/compile"` to enable AOT compilation for every constructed schema. Runs last, once the instance is fully built, because it hands the instance to compile(). The post-processor is expected to be reentrancy-guarded by its own implementation. - const pp = globalThis.__zod_globalConfig?.postProcessor; - if (pp) - pp(inst); - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("zod_brand"))); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -(core_a = globalThis).__zod_globalConfig ?? (core_a.__zod_globalConfig = {}); -const globalConfig = globalThis.__zod_globalConfig; -function core_config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -class $ZodCyclicError extends Error { - constructor() { - super(`Cannot parse a reference cycle that closes through a transform`); - this.name = "ZodCyclicError"; - } -} -/** Keyed off the context object every schema in one parse call already shares. */ -const STATE = "~memo"; -const NO_ISSUES = []; -// Receivers prefix paths in place, so the cache and every hand-out need their own copies. -function cloneIssues(issues) { - return issues.map((iss) => (iss.path ? { ...iss, path: iss.path.slice() } : { ...iss })); -} -const recursive = /*@__PURE__*/ new WeakMap(); -/** Whether this schema's subtree contains a cycle, so one parse can re-enter it. */ -function isRecursive(inst, stack) { - const cached = recursive.get(inst); - if (cached !== undefined) - return cached; - // Relative to the walk in progress, so not cached. - if (stack.has(inst)) - return true; - stack.add(inst); - let result = false; - const check = (child) => { - if (!result && child?._zod && isRecursive(child, stack)) - result = true; - }; - const def = inst._zod.def; - const kind = def.type; - switch (kind) { - case "object": { - // `Reflect.ownKeys` rather than `Object.keys`, so a cycle through a declared symbol key is still seen - for (const key of Reflect.ownKeys(def.shape)) - check(def.shape[key]); - check(def.catchall); - break; - } - case "array": - check(def.element); - break; - case "tuple": - for (const el of def.items) - check(el); - check(def.rest); - break; - case "record": - case "map": - check(def.keyType); - check(def.valueType); - break; - case "set": - check(def.valueType); - break; - case "union": - for (const el of def.options) - check(el); - break; - case "intersection": - check(def.left); - check(def.right); - break; - case "optional": - case "nullable": - case "default": - case "prefault": - case "catch": - case "readonly": - case "nonoptional": - case "promise": - case "success": - check(def.innerType); - break; - case "pipe": - check(def.in); - check(def.out); - break; - case "function": - check(def.input); - check(def.output); - break; - // reading `_zod.innerType` resolves the getter once and caches it - case "lazy": - check(inst._zod.innerType); - break; - // a leaf by choice: `parts` are regex fragments, not data positions - case "template_literal": - // leaves - case "string": - case "number": - case "int": - case "boolean": - case "bigint": - case "symbol": - case "undefined": - case "null": - case "void": - case "never": - case "any": - case "unknown": - case "date": - case "nan": - case "enum": - case "literal": - case "file": - case "transform": - case "custom": - break; - default: { - // a new built-in kind becomes a compile error here - kind; - // a user-defined kind can still hold children, and only its author knows where, so fall back to scanning the def — skipping accessors, since reading one can run user code - for (const key in def) { - const desc = Object.getOwnPropertyDescriptor(def, key); - if (!desc || desc.get) - continue; - const value = desc.value; - if (!value || typeof value !== "object") - continue; - if (value._zod) - check(value); - else if (Array.isArray(value)) - for (const el of value) - check(el); - } - } - } - stack.delete(inst); - recursive.set(inst, result); - return result; -} -/** - * Whether one parse can re-enter this schema, i.e. its subtree contains a cycle. - * Exported for `z.compile`, which refuses to compile such a schema: cycle - * breaking is driven from here off state keyed on the parse context, and a - * generated fast path has no context to key on. - */ -function isRecursiveSchema(inst) { - return isRecursive(inst, new Set()); -} -function bucketFor(state, inst) { - let bucket = state.buckets.get(inst); - if (!bucket) { - bucket = new Map(); - state.buckets.set(inst, bucket); - } - return bucket; -} -// Set immediately before delegating to core and cleared immediately after, so `alloc` registers only for a visit this module is driving. -let handoff; -// Allocated but unfinished entries. `alloc` and the matching pop both happen in the synchronous part of a parse, so they nest even when children are async, and one stack serves every schema. -const memoizer_open = []; -const memoizer_memo = { - alloc(_inst, payload, empty) { - const bucket = handoff; - if (!bucket) - return empty; - handoff = undefined; - const entry = { value: empty, issues: null }; - bucket.set(payload.value, entry); - memoizer_open.push(entry); - return empty; - }, - guard(inst) { - var _a; - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - // The value is a placeholder a back-edge is still waiting on, so the cycle closes through this transform. Its output can't exist in time to bind. - if (ctx.direction !== "backward" && isBackEdge(ctx, payload.value)) - throw new $ZodCyclicError(); - return base(payload, ctx); - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, - attach(inst) { - var _a; - let isRecursiveInst; - // `bucket` memoized for one parse; a recursive schema is re-entered many times and its bucket never changes - let lastCtx; - let lastBucket; - // Wraps `parse` in a deferred so it sees the container's final parse. Core's own deferred copies `parse` into `run` when there are no checks, and it ran first, so `run` is patched to match; with checks, `run` reads `parse` dynamically. - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred.push(() => { - const base = inst._zod.parse; - const wrapped = (payload, ctx) => { - if (isRecursiveInst === undefined) { - isRecursiveInst = isRecursive(inst, new Set()); - if (!isRecursiveInst) { - // Nothing here can ever fire, so take it back out. - inst._zod.parse = base; - if (inst._zod.run === wrapped) - inst._zod.run = base; - return base(payload, ctx); - } - } - const input = payload.value; - if (input === null || typeof input !== "object") - return base(payload, ctx); - let state = ctx[STATE]; - if (!state) { - state = { buckets: new Map(), backEdges: undefined }; - ctx[STATE] = state; - } - let bucket; - if (lastCtx === ctx) { - bucket = lastBucket; - } - else { - bucket = bucketFor(state, inst); - lastCtx = ctx; - lastBucket = bucket; - } - const hit = bucket.get(input); - if (hit) { - payload.value = hit.value; - if (hit.issues) { - if (hit.issues.length) - payload.issues.push(...cloneIssues(hit.issues)); - } - else { - // Still being parsed: its own checks cover it, so skip them here. - payload.memo = true; - state.backEdges ?? (state.backEdges = new Set()); - state.backEdges.add(hit.value); - } - return payload; - } - handoff = bucket; - const depth = memoizer_open.length; - const result = base(payload, ctx); - handoff = undefined; - // A container that rejected its input outright allocated nothing. - const entry = memoizer_open.length > depth ? memoizer_open.pop() : undefined; - // Both paths written out so the sync one allocates no closure. It runs once per node, and capturing here cost more than everything else combined. - if (result instanceof Promise) { - return result.then((r) => { - if (entry) - entry.issues = r.issues.length ? cloneIssues(r.issues) : NO_ISSUES; - return r; - }); - } - if (entry) - entry.issues = result.issues.length ? cloneIssues(result.issues) : NO_ISSUES; - return result; - }; - inst._zod.parse = wrapped; - if (inst._zod.run === base) - inst._zod.run = wrapped; - }); - }, -}; -/** The memoizer that gives containers cycle support. `zod` installs it by default; `zod/mini` opts in with `config({ memoizer: memoizer() })`. */ -function memoizer() { - return memoizer_memo; -} -/** Whether this value is a node a back-edge resolved to before it finished. */ -function isBackEdge(ctx, value) { - const backEdges = ctx[STATE]?.backEdges; - return backEdges !== undefined && value !== null && typeof value === "object" && backEdges.has(value); -} - - -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const cuid = /^[cC][0-9a-z]{6,}$/; -const cuid2 = /^[0-9a-z]+$/; -const ulid = /^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/; -const xid = /^[0-9a-vA-V]{20}$/; -const ksuid = /^[A-Za-z0-9]{27}$/; -const nanoid = /^[a-zA-Z0-9_-]{21}$/; -function nanoidOfLength(length) { - return new RegExp(`^[a-zA-Z0-9_-]{${length}}$`); -} -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ -const extendedDuration = /^[-+]?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)?)??$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. - * - * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -const uuid = (version) => { - if (!version) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(4))); -const uuid6 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(6))); -const uuid7 = /*@__PURE__*/ (/* unused pure expression or super */ null && (uuid(7))); -/** Practical email validation */ -const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -/** The classic emailregex.com regex for RFC 5322-compliant emails */ -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = (/* unused pure expression or super */ null && (unicodeEmail)); -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -// Single character class, not an alternation: the two properties overlap (U+1F9B0-U+1F9B3), so `(A|B)+` backtracks exponentially on a failed match. -const _emoji = `^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const regexes_ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/; -const mac = (delimiter) => { - const escapedDelim = util.escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -const cidrv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const regexes_base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const regexes_base64url = /^[A-Za-z0-9_-]*$/; -// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address -// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -const regexes_hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^(?=.{1,253}$)([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,63}$/; -const httpProtocol = /^https?$/; -// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) E.164: leading digit must be 1-9; total digits (excluding '+') between 7-15 -const e164 = /^\+[1-9]\d{6,14}$/; -// Credit card shape: 12–19 digits, optionally separated by single spaces or single hyphens. ISO/IEC 7812 caps the PAN at 19 digits; 12 is the shortest issued length (Maestro). -const creditCard = /^\d(?:[ -]?\d){11,18}$/; -const dateSource = `(?:(?:\\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])))`; -/** Anchors a pattern source. The interpolation lives here rather than at the call site because - * esbuild will not drop a `@__PURE__` call whose own argument interpolates a variable, but it - * will drop `anchor(dateSource)`. Keeping it inline pinned `date` into every bundle. */ -function regexes_anchor(source) { - return new RegExp(`^${source}$`); -} -const regexes_date = /*@__PURE__*/ regexes_anchor(dateSource); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : args.seconds - ? `${hhmm}:[0-5]\\d(?:\\.\\d+)?` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function regexes_time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetime(args) { - const opts = ["Z"]; - // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - // RFC 3339 mandates seconds wherever the time carries a `Z` or an offset, so only the unqualified form `local` adds may omit them - const qualified = `${timeSource({ precision: args.precision, seconds: true })}(?:${opts.join("|")})`; - const timeRegex = args.local ? `${qualified}|${timeSource({ precision: args.precision })}` : qualified; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const regexes_string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number = /^-?\d+(?:\.\d+)?$/; -const regexes_boolean = /^(?:true|false)$/i; -const _null = /^null$/i; - -const _undefined = /^undefined$/i; - -// regex for string with no uppercase letters -const lowercase = /^[^A-Z]*$/; -// regex for string with no lowercase letters -const uppercase = /^[^a-z]*$/; -// regex for hexadecimal strings (any length) -const regexes_hex = /^[0-9a-fA-F]*$/; -// Hash regexes for different algorithms and encodings -// Helper function to create base64 regex with exact length and padding -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -// Helper function to create base64url regex with exact length (no padding) -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -// MD5 (16 bytes): base64 = 24 chars total (22 + "==") -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(22, "=="))); -const md5_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(22))); -// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(27, "="))); -const sha1_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(27))); -// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(43, "="))); -const sha256_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(43))); -// SHA384 (48 bytes): base64 = 64 chars total (no padding) -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(64, ""))); -const sha384_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(64))); -// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64(86, "=="))); -const sha512_base64url = /*@__PURE__*/ (/* unused pure expression or super */ null && (fixedBase64url(86))); - -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -/** Default `when` for size-based checks: run only on non-nullish values with a `size`. */ -const _whenHasSize = (payload) => { - const val = payload.value; - return !util.nullish(val) && val.size !== undefined; -}; -/** Default `when` for length-based checks: run only on non-nullish values with a `length`. */ -const _whenHasLength = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; -}; -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_big", - maximum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin: numericOriginMap[typeof payload.value] ?? origin, - code: "too_small", - minimum: typeof def.value === "object" ? def.value.getTime() : def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = -/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? // `value % 0n` throws, and nothing is a multiple of zero — the number branch already fails this way via NaN - def.value !== BigInt(0) && payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - inclusive: true, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodCheckBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = util.BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - }; -}))); -const $ZodCheckMaxSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMinSize = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: util.getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckSizeEquals = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasSize); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: util.getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // Strings are measured in Unicode code points, not UTF-16 units. A code point is at most two units, so a string that already fits in units fits in code points; only an overflow has to be counted. - const length = typeof input === "string" && units > def.maximum ? codePointLength(input) : units; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so fewer units than the floor can never reach it and twice the floor always clears it. Only in between is the exact count in doubt. - const length = typeof input === "string" && units >= def.minimum && units < def.minimum * 2 - ? codePointLength(input) - : units; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = _whenHasLength); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const units = input.length; - // A code point is one or two UTF-16 units, so outside `[length, length * 2]` units the target is missed either way — and missed in the same direction in both measures. - const length = typeof input === "string" && units >= def.length && units <= def.length * 2 - ? codePointLength(input) - : units; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - // `String.prototype.includes(sub, position)` matches `sub` at `position` - // OR LATER, so the pattern must allow at least `position` leading chars - // (`{N,}`), not exactly `position` chars (`{N}`). - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position},}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...util.prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}))); -const $ZodCheckMimeType = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -class Doc { - constructor(args = [], closed = {}) { - this.content = []; - this.indent = 0; - this.args = args; - this.closed = closed; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const content = this?.content ?? [``]; - const factory = new F(...Object.keys(this.closed), `return function (${this.args.join(", ")}) {\n${content.join("\n")}\n};`); - return factory(...Object.values(this.closed)); - } -} - - - -/* Computing the message eagerly is expensive (pretty-printed JSON of all - * issues), so defer it until first read. The accessor functions and - * descriptors are shared across instances to keep error construction - * cheap; the computed message is cached on the internals object. The - * setter preserves plain assignment semantics for consumers that - * overwrite `message`. */ -function _getMessage() { - const internals = this._zod; - internals.message ?? (internals.message = JSON.stringify(internals.def, jsonStringifyReplacer, 2)); - return internals.message; -} -function _setMessage(value) { - this._zod.message = value; -} -const _messageDesc = { - get: _getMessage, - set: _setMessage, - enumerable: true, - configurable: true, -}; -const errors_zodDesc = { value: undefined, enumerable: false }; -const _issuesDesc = { value: undefined, enumerable: false }; -/* Prototypes that already carry the lazy `toString`. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedToString = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -const errors_initializer = (inst, def) => { - inst.name = "$ZodError"; - errors_zodDesc.value = inst._zod; - Object.defineProperty(inst, "_zod", errors_zodDesc); - _issuesDesc.value = def; - Object.defineProperty(inst, "issues", _issuesDesc); - // Clear the shared slots; a retained `value` pins the last error's issues. - errors_zodDesc.value = undefined; - _issuesDesc.value = undefined; - Object.defineProperty(inst, "message", _messageDesc); - /* `toString` lives as a non-enumerable lazy getter on the shared - * prototype; on first access it caches a per-instance closure so - * detached usage still works. */ - const proto = Object.getPrototypeOf(inst); - if (!_installedToString.has(proto)) { - _installedToString.add(proto); - Object.defineProperty(proto, "toString", { - configurable: true, - enumerable: false, - get() { - const value = () => this.message; - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, "toString", { value, configurable: true, writable: true }); - }, - }); - } -}; -const $ZodError = $constructor("$ZodError", errors_initializer); -const $ZodRealError = $constructor("$ZodError", errors_initializer, undefined, { - Parent: Error, -}); -/** Get-or-create `obj[key]` as an own data property. A path segment naming an inherited member - * ("toString", "constructor") would otherwise read through to the prototype, and assigning - * "__proto__" would hit the setter instead of creating a key. */ -function errors_node(obj, key, make) { - if (!Object.prototype.hasOwnProperty.call(obj, key)) { - if (key === "__proto__") { - Object.defineProperty(obj, key, { value: make(), writable: true, enumerable: true, configurable: true }); - } - else { - obj[key] = make(); - } - } - return obj[key]; -} -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - errors_node(fieldErrors, sub.path[0], () => []).push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error, path = []) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - // `_errors` is reserved by this legacy format, so merge a matching path segment into the current node instead of treating its array as a child. - if (el === "_errors") { - if (terminal) - curr._errors.push(mapper(issue)); - i++; - continue; - } - // A path element may collide with an inherited property name such as - // "__proto__" or "constructor". Truthiness checks read the prototype - // (so no node is created, then ._errors.push throws), and bracket - // assignment of "__proto__" hits the setter instead of creating an - // own key. Guard the read with hasOwnProperty and create the node - // with defineProperty so any path element becomes a real own key. - if (!Object.prototype.hasOwnProperty.call(curr, el)) { - Object.defineProperty(curr, el, { - value: { _errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - const node = curr[el]; - if (terminal) { - node._errors.push(mapper(issue)); - } - curr = node; - i++; - } - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, [...path, ...issue.path])); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, [...path, ...issue.path]); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - // el may collide with an inherited property name ("__proto__", - // "constructor", ...); ??= reads the prototype so the node is never - // created and curr.errors.push throws. Guard with hasOwnProperty and - // create the node with defineProperty so "__proto__" becomes a real - // own key rather than invoking the prototype setter. - if (!Object.prototype.hasOwnProperty.call(curr.properties, el)) { - Object.defineProperty(curr.properties, el, { - value: { errors: [] }, - enumerable: true, - writable: true, - configurable: true, - }); - } - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_a = curr.items)[el] ?? (_a[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - - - - -// Always both keys, so the `_params` read site in `_parse` sees one object shape rather than two. -function finalizeParams(callee, params) { - return { callee: params?.callee ?? callee, Err: params?.Err }; -} -const parse_parse = (_Err) => { - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, _params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parse = /* @__PURE__*/ parse_parse($ZodRealError); -const parse_parseAsync = (_Err) => { - const fn = async (schema, value, _ctx, params) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))); - captureStackTrace(e, params?.callee ?? fn); - throw e; - } - return result.value; - }; - return fn; -}; -const core_parse_parseAsync = /* @__PURE__*/ parse_parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); -// registry mirrors of the compiler's sentinels, so this module never imports the compiler -const COMPILE_INVALID = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.invalid"))); -const COMPILE_FALLBACK = /* @__PURE__ */ (/* unused pure expression or super */ null && (Symbol.for("zod.compile.fallback"))); -// Deliberately tiny, because v8 will not inline a body carrying the fallback's object literals and throw. Everything that is not the compiled happy path lives in validateFallback, and that split is worth ~35% on a compiled schema. -const parse_validate = ((schema, value, _ctx) => { - const validator = schema._zod.bag.validator; - if (validator !== undefined && validator(value) !== COMPILE_INVALID) - return true; - return validateFallback(schema, value, _ctx); -}); -function validateFallback(schema, value, _ctx) { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const fallbackRun = schema._zod.bag.fallbackRun; - let result; - if (fallbackRun) { - // skip nested fast paths on the fallback, so user callbacks keep the at-most-twice bound - ctx[COMPILE_FALLBACK] = true; - result = fallbackRun({ value, issues: [] }, ctx); - } - else { - result = schema._zod.run({ value, issues: [] }, ctx); - } - if (result instanceof Promise) { - throw new core.$ZodAsyncError(); - } - return result.issues.length === 0; -} -// no fast path: the compiler keeps async parses on the runtime, because a promise-returning callback that is not declared async compiles to a throw -const parse_validateAsync = async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: true } : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length === 0; -}; -const parse_encode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return parse(schema, value, ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const encode = /* @__PURE__*/ parse_encode($ZodRealError); -const parse_decode = (_Err) => { - const parse = parse_parse(_Err); - const fn = (schema, value, _ctx, _params) => { - return parse(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decode = /* @__PURE__*/ parse_decode($ZodRealError); -const parse_encodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return (await parseAsync(schema, value, ctx, finalizeParams(fn, _params))); - }; - return fn; -}; -const encodeAsync = /* @__PURE__*/ parse_encodeAsync($ZodRealError); -const parse_decodeAsync = (_Err) => { - const parseAsync = parse_parseAsync(_Err); - const fn = async (schema, value, _ctx, _params) => { - return await parseAsync(schema, value, _ctx, finalizeParams(fn, _params)); - }; - return fn; -}; -const decodeAsync = /* @__PURE__*/ parse_decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); - -const versions_version = { - major: 4, - minor: 5, - patch: 4, -}; - - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const defChecks = inst._zod.def.checks; - // if inst is itself a checks.$ZodCheck, run it as a check - const checks = inst._zod.traits.has("$ZodCheck") - ? [inst, ...(defChecks ?? [])] - : defChecks?.length - ? [...defChecks] - : []; - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - if (payload.memo) - return payload; - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - if (explicitlyAborted(payload)) - continue; - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - attachSchema(payload.issues, currLen, inst); - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - // abort if the canary is aborted - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - // run checks first, then - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - // run canary initial pass (no checks) - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - // forward - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } -}, { - // Wrappers extend this by installing a richer factory over it; reading it eagerly would defeat the laziness. - get "~standard"() { - return hide(this, "~standard", standardProps(this)); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, -}); -/** The Standard Schema surface for `inst`. Shared so wrappers can extend it without forcing it. */ -const toStandardResult = (r) => r.success ? { value: r.data } : { issues: r.error?.issues }; -function standardProps(inst) { - return { - validate: (value) => { - try { - return toStandardResult(safeParse(inst, value)); - } - catch (_) { - return safeParseAsync(inst, value).then(toStandardResult); - } - }, - vendor: "zod", - version: 1, - }; -} - -const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? regexes_string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } - else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -/** The `://` guard rejected the input before the URL constructor saw it. */ -const URL_BAD_FORMAT = 1; -/** The URL constructor rejected the input. */ -const URL_UNPARSEABLE = 2; -/** Parses a URL for `$ZodURL`, applying the one guard the URL constructor cannot express. Returns the parsed URL, or a code naming the stage that rejected it — the runtime needs that distinction to pick an issue note, and compiled code only needs to know it is not a URL. */ -function parseURLObject(trimmed, def) { - // When normalize is off, require :// for http/https URLs. This prevents strings like "http:example.com" or "https:/path" from being silently accepted - if (!def.normalize && def.protocol?.source === httpProtocol.source && !/^https?:\/\//i.test(trimmed)) { - return URL_BAD_FORMAT; - } - try { - // @ts-ignore - return new URL(trimmed); - } - catch { - return URL_UNPARSEABLE; - } -} -const asciiTabOrNewline = /[\t\n\r]/g; -/** The URL parser deletes every ASCII tab, LF and CR from its input before it parses, so `new URL("https://exa\nmple.com")` reports on `example.com`. Applying the same deletion to the returned value closes the half of that divergence which can move the host; the parser's other rewrite, stripping C0 controls at the edges, cannot. */ -function stripTabAndNewline(value) { - return value.replace(asciiTabOrNewline, ""); -} -function urlHostnameOk(url, hostname) { - hostname.lastIndex = 0; - return hostname.test(url.hostname); -} -function urlProtocolOk(url, protocol) { - protocol.lastIndex = 0; - return protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol); -} -const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - // Trim whitespace from input - const trimmed = payload.value.trim(); - const url = parseURLObject(trimmed, def); - if (url === URL_BAD_FORMAT) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid URL format", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (url === URL_UNPARSEABLE) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - return; - } - if (def.hostname && !urlHostnameOk(url, def.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - if (def.protocol && !urlProtocolOk(url, def.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - // Set the output value based on normalize flag - payload.value = def.normalize ? url.href : stripTabAndNewline(trimmed); - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - if (def.length !== undefined && (!Number.isInteger(def.length) || def.length < 1)) - throw new Error(`Invalid nanoid length: ${def.length}`); - def.pattern ?? (def.pattern = def.length === undefined ? nanoid : nanoidOfLength(def.length)); - $ZodStringFormat.init(inst, def); -}); -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link $ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); - // these two drop the offset or seconds `date-time` requires — on the bag not the def, since `z.string().check(...)` lands the format on a different schema - if (def.local || def.precision === -1) { - inst._zod.bag.laxFormat = true; - inst._zod.onattach.push((s) => { - s._zod.bag.laxFormat = true; - }); - } -}); -const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = regexes_date); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = regexes_time(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -/** An IPv6 address is written with hex digits, colons and dots, and nothing else. The guard is what makes the check below an IPv6 check: `new URL("http://[...]")` parses an authority, not an address, so `@` and `\` re-delimit it and `"::@1\\"` validates against the host `0.0.0.1`. The URL parser also deletes ASCII tab, LF and CR rather than failing, which is how `"::1\n"` validated as `::1`. */ -const ipv6Alphabet = /^[0-9a-fA-F:.]+$/; -function isValidIPv6(value) { - if (!ipv6Alphabet.test(value)) - return false; - try { - // @ts-ignore - new URL(`http://[${value}]`); - return true; - } - catch { - return false; - } -} -const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = regexes_ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - if (!isValidIPv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = regexes.mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}))); -const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -function isValidCIDRv6(value) { - const parts = value.split("/"); - if (parts.length !== 2) - return false; - const [address, prefix] = parts; - if (!prefix) - return false; - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - return false; - if (prefixNum < 0 || prefixNum > 128) - return false; - return isValidIPv6(address); -} -const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (!isValidCIDRv6(payload.value)) { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - // atob ignores whitespace, so reject it up front. - if (/\s/.test(data)) - return false; - if (data.length % 4 !== 0) - return false; - try { - // @ts-ignore - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!regexes_base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = regexes_base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -////////////////////////////// ZodCreditCard ////////////////////////////// -const CC_SANITIZE = /[- ]/g; -/** Luhn checksum on a digit-only string. Adapted from valibot (MIT). */ -function isLuhnAlgo(digits) { - let length = digits.length; - let bit = 1; - let sum = 0; - while (length) { - const value = +digits[--length]; - bit ^= 1; - sum += bit ? [0, 2, 4, 6, 8, 1, 3, 5, 7, 9][value] : value; - } - return sum % 10 === 0; -} -function isValidCreditCard(input) { - if (!regexes.creditCard.test(input)) - return false; - return isLuhnAlgo(input.replace(CC_SANITIZE, "")); -} -const $ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCreditCard", (inst, def) => { - // Shape only — the Luhn check below is not expressible as a pattern, so consumers of `pattern` (JSON Schema, template literals) get the length and separator rules alone. - def.pattern ?? (def.pattern = regexes.creditCard); - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidCreditCard(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "credit_card", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - // @ts-ignore - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}))); -const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? String(input) - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checks -}); -const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes_boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}))); -const $ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodBigIntFormat", (inst, def) => { - checks.$ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}))); -const $ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes.undefined; - inst._zod.values = new Set([undefined]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}))); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, Array(input.length), ctx) : Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handlePropertyResult(result, final, key, input, optin, optout) { - const isPresent = key in input; - const isOptionalOut = optout === "optional"; - // The middle rung means "absence permitted, nothing supplied in its place", so an absent key contributes nothing — whatever the schema made of `undefined` is invented, not substituted. Only `optional` reaches this with a value: `defaulted` substitutes, and a schema that isn't optional-out has to keep the key. - if (!isPresent && isOptionalOut && optin === "optional") { - return; - } - if (result.issues.length) { - // For optional-in/out schemas, ignore errors on absent keys. - if (optin !== undefined && isOptionalOut && !isPresent) { - return; - } - final.issues.push(...prefixIssues(key, result.issues)); - } - if (!isPresent && optin === undefined) { - if (!result.issues.length) { - final.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [key], - }); - } - return; - } - if (result.value === undefined) { - if (isPresent) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -// one shared instance; a fresh [] per schema cost 56 bytes retained -const NO_SYMBOL_KEYS = []; -function normalizeDef(def) { - const keys = Object.keys(def.shape); - const ownSymbols = Object.getOwnPropertySymbols(def.shape); - const symbolKeys = ownSymbols.length ? ownSymbols : NO_SYMBOL_KEYS; - // aliases `keys` when there are no symbols, so a string-only shape keeps one array - const allKeys = symbolKeys.length ? [...keys, ...symbolKeys] : keys; - for (const k of allKeys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${String(k)}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - allKeys, - symbolKeys, - // string-only: handleCatchall matches it against `for...in`, which never yields a symbol - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - const optin = _catchall.optin; - const optout = _catchall.optout; - for (const key in input) { - // Must precede the __proto__ branch: a declared key is not unrecognized, even though the shape loop deliberately strips __proto__ from the parsed output. - if (keySet.has(key)) - continue; - // Don't copy an undeclared __proto__ into the result; assignment to a plain {} would replace the result prototype. But in strict mode it is still an unknown key, so report it before skipping. - if (key === "__proto__") { - if (t === "never") - unrecognized.push(key); - continue; - } - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - // Describes the shape of the input, not the validity of the parsed value, so it never aborts. The parse still fails; the schema's own checks just get to run first, and an enclosing intersection can reconcile the key against a sibling operand. - continue: true, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -// Whichever object a def's `shape` currently answers from: the one the caller passed until the first read, the frozen copy after it. Keyed by def, so a def rebuilt by a builder is simply absent rather than inheriting the source's. Read its keys with `Object.keys`, which does not invoke them — that is what lets a discriminated union check its discriminator without resolving an option whose getters reference the union being constructed. -const propShapes = new WeakMap(); -const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - // const sh = def.shape; - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - propShapes.set(def, sh); - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - propShapes.set(def, newSh); - return newSh; - }, - }); - } - const _normalized = util_cached(() => normalizeDef(def)); - defineLazyInternal(inst, "propValues", (zod) => { - const shape = zod.def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - if (!Object.prototype.hasOwnProperty.call(propValues, key)) { - assignProp(propValues, key, new Set()); - } - for (const v of field.values) - propValues[key].add(v); - // An omittable slot reads back as undefined at a discriminator lookup, so it has to claim undefined: two options that can both omit the key are not discriminable on it. - if (field.optin !== undefined) - propValues[key].add(undefined); - } - } - return propValues; - }); - const isObject = util_isObject; - const catchall = def.catchall; - let value; - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const proms = []; - const shape = value.shape; - for (const key of value.allKeys) { - if (key === "__proto__") - continue; - const el = shape[key]; - const optin = el._zod.optin; - const optout = el._zod.optout; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input, optin, optout))); - } - else { - handlePropertyResult(r, payload, key, input, optin, optout); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = util_cached(() => normalizeDef(def)); - const memo = globalConfig.memoizer; - const generateFastpass = (shape) => { - const normalized = _normalized.value; - const syms = normalized.symbolKeys; - // a symbol has no source literal, so it is read as `syms[i]` off the closed-over scope - const doc = new Doc(["payload", "ctx"], { shape, inst, memo, syms }); - const parseStr = (k) => `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - // Prefixes in place, like util.prefixIssues does for every interpreted path. - const prefixStr = (id, k) => ` - for (let i = 0; i < ${id}.issues.length; i++) { - const iss = ${id}.issues[i]; - iss.path = iss.path ? [${k}, ...iss.path] : [${k}]; - payload.issues.push(iss); - }`; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.allKeys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(memo ? `const newResult = memo.alloc(inst, payload, {}, ctx);` : `const newResult = {};`); - for (const key of normalized.allKeys) { - if (key === "__proto__") - continue; - const id = ids[key]; - const k = typeof key === "symbol" ? `syms[${syms.indexOf(key)}]` : util_esc(key); - const isPresent = `${k} in input`; - const schema = shape[key]; - const optin = schema?._zod?.optin; - const isOptionalIn = optin !== undefined; - const isOptionalOut = schema?._zod?.optout === "optional"; - doc.write(`const ${id} = ${parseStr(k)};`); - if (isOptionalIn && isOptionalOut) { - // For optional-in/out schemas, ignore errors on absent keys — and, like the interpreted path, drop the value produced alongside them. The middle rung goes further: it permits absence without supplying anything in its place, so an absent key contributes nothing at all. - const assign = optin === "optional" ? `${id}_present` : `${id}.value !== undefined || ${id}_present`; - doc.write(` - const ${id}_present = ${isPresent}; - if (!${id}.issues.length || ${id}_present) { - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${assign}) { - newResult[${k}] = ${id}.value; - } - } - - `); - } - else if (!isOptionalIn) { - doc.write(` - const ${id}_present = ${isPresent}; - if (${id}.issues.length) {${prefixStr(id, k)} - } - if (!${id}_present && !${id}.issues.length) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: undefined, - path: [${k}] - }); - } - - if (${id}_present) { - newResult[${k}] = ${id}.value; - } - - `); - } - else { - doc.write(` - if (${id}.issues.length) {${prefixStr(id, k)} - } - - if (${id}.value === undefined) { - if (${isPresent}) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - // closing `shape` in is what pays: turbofan specializes the parser against that one shape object, so every `shape[k]._zod.run` folds to a known callee. as a parameter it stays a generic load and measures 13% slower even with the forwarding frame gone - return doc.compile(); - }; - let fastpass; - const isObject = util_isObject; - const jit = !globalConfig.jitless; - const allowsEval = util_allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, core_config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.options.some((o) => o._zod.optin === "defaulted") - ? "defaulted" - : zod.def.options.some((o) => o._zod.optin !== undefined) - ? "optional" - : undefined); - defineLazyInternal(inst, "optout", (zod) => zod.def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazyInternal(inst, "values", (zod) => { - if (zod.def.options.every((o) => o._zod.values)) { - return new Set(zod.def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - if (zod.def.options.every((o) => o._zod.pattern)) { - const patterns = zod.def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const matches = []; - for (let i = 0; i < results.length; i++) { - if (results[i].issues.length === 0) - matches.push(i); - } - if (matches.length === 1) { - final.value = results[matches[0]].value; - return final; - } - if (matches.length === 0) { - // No matches - same as regular union - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config()))), - }); - } - else { - // Multiple matches - exclusive union failure - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - matches, - }); - } - return final; -} -const $ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const first = def.options.length === 1 ? def.options[0]._zod.run : null; - inst._zod.parse = (payload, ctx) => { - if (first) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}))); -/** Returns the option of `union` whose discriminator claims `value`. */ -function getDiscriminatedOption(union, value) { - const internals = union._zod; - let map = internals.bag.optionsMap; - if (!map) { - map = new Map(); - const { options, discriminator } = internals.def; - for (const option of options) { - // First declaration wins, matching the order the parse path resolves a duplicate in. - for (const v of option._zod.propValues?.[discriminator] ?? []) - if (!map.has(v)) - map.set(v, option); - } - internals.bag.optionsMap = map; - } - return map.get(value); -} -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazyInternal(inst, "propValues", (zod) => { - const propValues = {}; - for (const option of zod.def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${zod.def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!Object.prototype.hasOwnProperty.call(propValues, k)) { - assignProp(propValues, k, new Set()); - } - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - // Checked now rather than in the lookup map below, so an option that lacks the discriminator fails at the `discriminatedUnion` call instead of on the first object parsed. Options whose shape cannot be enumerated without resolving it — pipes, lazies, and objects rebuilt by a builder such as `.extend()` — are left to the map. - def.options.forEach((option, i) => { - const propShape = propShapes.get(option._zod.def); - if (propShape && !Object.prototype.hasOwnProperty.call(propShape, def.discriminator)) { - throw new Error(`Invalid discriminated union option at index "${i}"`); - } - }); - const disc = util_cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util_isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - // Fall back to union matching when the fast discriminator path fails: - // - explicitly enabled via unionFallback, or - // - during backward direction (encode), since codec-based discriminators have different values in forward vs backward directions - if (def.unionFallback || ctx.direction === "backward") { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - options: Array.from(disc.value.keys()), - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function schemas_mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - if (Object.prototype.hasOwnProperty.call(newObj, "__proto__")) - delete newObj.__proto__; - for (const key of sharedKeys) { - if (key === "__proto__") - continue; - const sharedValue = schemas_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = schemas_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - // Track which side(s) reject each key. A key rejection is reported only when BOTH sides reject it, so a key owned by one branch survives the other's key schema. strictObject reports these as unrecognized_keys; a record with an open key schema reports one invalid_key per key. - const unrecKeys = new Map(); - let unrecIssue; - const keyIssues = new Map(); - const collect = (iss, side) => { - let keys; - if (iss.code === "unrecognized_keys" && !iss.path?.length) { - unrecIssue ?? (unrecIssue = iss); - keys = iss.keys; - } - else if (iss.code === "invalid_key" && iss.origin === "record" && iss.path?.length === 1) { - const k = String(iss.path[0]); - if (!keyIssues.has(k)) - keyIssues.set(k, iss); - keys = [k]; - } - else { - return false; - } - for (const k of keys) { - if (!unrecKeys.has(k)) - unrecKeys.set(k, {}); - unrecKeys.get(k)[side] = true; - } - return true; - }; - for (const iss of left.issues) { - if (!collect(iss, "l")) - result.issues.push(iss); - } - for (const iss of right.issues) { - if (!collect(iss, "r")) - result.issues.push(iss); - } - // Report only keys rejected by BOTH sides - const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k); - if (bothKeys.length) { - const aggregated = unrecIssue ? bothKeys.filter((k) => unrecIssue.keys.includes(k)) : []; - if (aggregated.length) - result.issues.push({ ...unrecIssue, keys: aggregated }); - for (const k of bothKeys) { - if (!aggregated.includes(k) && keyIssues.has(k)) - result.issues.push(keyIssues.get(k)); - } - } - const merged = schemas_mergeValues(left.value, right.value); - if (!merged.valid) { - if (aborted(result)) - return result; - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = memo ? memo.alloc(inst, payload, [], ctx) : []; - const proms = []; - const optinStart = getTupleOptStart(items, "optin"); - const optoutStart = getTupleOptStart(items, "optout"); - if (!def.rest) { - if (input.length < optinStart) { - payload.issues.push({ - code: "too_small", - minimum: optinStart, - inclusive: true, - input, - inst, - origin: "array", - }); - return payload; - } - if (input.length > items.length) { - payload.issues.push({ - code: "too_big", - maximum: items.length, - inclusive: true, - input, - inst, - origin: "array", - }); - } - } - // Run every item in parallel, collecting results into an indexed array. The post-processing in `handleTupleResults` walks them in order so it can decide whether an absent optional-output error can truncate the tail or must be reported to preserve required output. - const itemResults = new Array(items.length); - for (let i = 0; i < items.length; i++) { - const r = items[i]._zod.run({ value: input[i], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((rr) => { - itemResults[i] = rr; - })); - } - else { - itemResults[i] = r; - } - } - if (def.rest) { - let i = items.length - 1; - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ value: el, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((r) => handleTupleResult(r, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => handleTupleResults(itemResults, payload, items, input, optoutStart)); - } - return handleTupleResults(itemResults, payload, items, input, optoutStart); - }; -}))); -function getTupleOptStart(items, key) { - for (let i = items.length - 1; i >= 0; i--) { - // optin is a three-rung ladder so any rung above `undefined` permits an absent slot; optout stays two-valued. - const omittable = key === "optin" ? items[i]._zod.optin !== undefined : items[i]._zod.optout === "optional"; - if (!omittable) - return i + 1; - } - return 0; -} -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...util.prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -function handleTupleResults(itemResults, final, items, input, optoutStart) { - // Walk results in order. Mirror $ZodObject's swallow-on-absent-optional rule, but only after `optoutStart`: the first index where the output tuple tail can be absent. - for (let i = 0; i < items.length; i++) { - const r = itemResults[i]; - const isPresent = i < input.length; - // The array analog of `handlePropertyResult`'s absent-key early return: the middle rung permits absence without supplying anything in its place, so the tail truncates here instead of materializing whatever the item made of `undefined`. - if (!isPresent && i >= optoutStart && items[i]._zod.optin === "optional") { - final.value.length = i; - break; - } - if (r.issues.length) { - if (!isPresent && i >= optoutStart) { - final.value.length = i; - break; - } - final.issues.push(...util.prefixIssues(i, r.issues)); - } - final.value[i] = r.value; - } - // Drop trailing slots that produced `undefined` for absent input - // (the array analog of an absent optional key on an object). The - // `i >= input.length` floor is critical: an explicit `undefined` - // *inside* the input must be preserved even when the schema is - // optional-out (e.g. `z.string().or(z.undefined())` accepting an - // explicit undefined value). - for (let i = final.value.length - 1; i >= input.length; i--) { - if (items[i]._zod.optout === "optional" && final.value[i] === undefined) { - final.value.length = i; - } - else { - break; - } - } - return final; -} -const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - const memo = globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values && !def.partial) { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - // A declared __proto__ is stripped but is not an unrecognized key. - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - continue; - } - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - if (def.mode === "loose") { - // skip __proto__ so it can't replace the result prototype via the assignment setter on the plain {} we build into - if (key === "__proto__") - continue; - payload.value[key] = input[key]; - } - else { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - else { - payload.value = memo ? memo.alloc(inst, payload, {}, ctx) : {}; - // An enumerable key schema declares which keys the record owns, so a key outside the set is unrecognized. A non-enumerable one (regex, refine) is a constraint every key must satisfy, so a failing key is invalid. Only the former is reconcilable against the other side of an intersection. - let unrecognized; - // Reflect.ownKeys for Symbol-key support; filter non-enumerable to match z.object() - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - if (!Object.prototype.propertyIsEnumerable.call(input, key)) - continue; - let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - // Numeric string fallback: if key is a numeric string and failed, retry with Number(key). This handles z.number(), z.literal([1, 2, 3]), and unions containing numeric literals - const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length; - if (checkNumericKey) { - const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx); - if (retryResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (retryResult.issues.length === 0) { - keyResult = retryResult; - } - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - // Pass through unchanged - payload.value[key] = input[key]; - } - else if (values) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - else { - // Default "strict" behavior: error on invalid key - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - // the guard above tests the raw input key, but the key schema can normalize an ordinary key into __proto__; re-check the key we actually write under - const outKey = keyResult.value; - if (outKey === "__proto__") - continue; - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[outKey] = result.value; - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - continue: true, - }); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Map(), ctx) : new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - if (valueResult.issues.length) { - if (util.propertyKeyTypes.has(typeof key)) { - final.issues.push(...util.prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => util.finalizeIssue(iss, ctx, core.config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - const memo = core.globalConfig.memoizer; - memo?.attach(inst); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = memo ? memo.alloc(inst, payload, new Set(), ctx) : new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}))); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - const patternValues = values.filter((k) => propertyKeyTypes.has(typeof k)); - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(patternValues.length ? `^(${patternValues.map((o) => escapeRegex(o.toString())).join("|")})$` : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - const values = new Set(def.values); - inst._zod.values = values; - // unmatchable fallback, RE2-safe: an empty alternation would compile to /^()$/, which matches "" - inst._zod.pattern = new RegExp(def.values.length - ? `^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$` - : "^[^\\s\\S]$"); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - // @ts-ignore - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}))); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - globalConfig.memoizer?.guard(inst); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(payload, result) { - // A substituting schema that still failed has no usable answer; yield undefined. Its issues are simply dropped: it ran on a payload of its own, so there is no shared array to truncate and nothing of the caller's to lose with it. - payload.value = result.issues.length ? undefined : result.value; - return payload; -} -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - // .optional() propagates absence rather than substituting for it, so a defaulted inner keeps its rung. - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - inst._zod.optout = "optional"; - defineLazyInternal(inst, "values", (zod) => { - const values = zod.def.innerType._zod.values; - return values ? new Set([...values, undefined]) : undefined; - }); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (payload.value === undefined) { - // Only the top rung substitutes a value for absence; everything else leaves it intact, which is what .optional() means. - if (def.innerType._zod.optin !== "defaulted") - return payload; - // Its own payload, for the same reason $ZodCatch gets one: a pipe forwards an unrecognized key through the caller's issues array, and this must not read that as the substituting schema failing and drop it. - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) - return result.then((result) => handleOptionalResult(payload, result)); - return handleOptionalResult(payload, result); - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodExactOptional = /*@__PURE__*/ $constructor("$ZodExactOptional", (inst, def) => { - // Call parent init - inherits optin/optout = "optional" - $ZodOptional.init(inst, def); - // Override values/pattern to NOT add undefined - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "pattern", (zod) => zod.def.innerType._zod.pattern); - // Override parse to just delegate (no undefined handling) - inst._zod.parse = (payload, ctx) => { - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "pattern", (zod) => { - const pattern = zod.def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazyInternal(inst, "values", (zod) => { - return zod.def.innerType._zod.values ? new Set([...zod.def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - // Forward direction (decode): allow null to pass through - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply defaults for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - // Forward direction: continue with default handling - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "defaulted"; - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply prefault for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => { - const v = zod.def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new core.$ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}))); -function handleCatchResult(payload, result, def, ctx) { - if (!result.issues.length) { - payload.value = result.value; - // The value carries up, so the flag describing it has to carry with it: a back-edge into a node still being parsed must not be frozen by an enclosing readonly, and its checks belong to the node itself. Guarded so the ordinary case adds no own property. - if (result.memo) - payload.memo = true; - return payload; - } - // Spread the inner's own payload, not ours: `value` has to stay the input the catch was handed, and the inner ran on a payload of its own so its issues are already private to this call. - payload.value = def.catchValue({ - ...result, - value: payload.value, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, core_config())), - }, - input: payload.value, - }); - return payload; -} -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType._zod.optin === "defaulted" ? "defaulted" : "optional"); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType._zod.optout); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply catch logic - const result = def.innerType._zod.run({ value: payload.value, issues: [] }, ctx); - if (result instanceof Promise) { - return result.then((result) => handleCatchResult(payload, result, def, ctx)); - } - return handleCatchResult(payload, result, def, ctx); - }; -}); -const $ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}))); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - // Any issue stops the pipe, so a failing refinement never feeds its transform. An unrecognized key is the exception: it describes the input's extra properties, not the value being piped, and an enclosing intersection may yet reconcile it. - if (left.issues.some((iss) => iss.code !== "unrecognized_keys")) { - // prevent further checks - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - util.defineLazyInternal(inst, "values", (zod) => zod.def.in._zod.values); - util.defineLazyInternal(inst, "optin", (zod) => zod.def.in._zod.optin); - util.defineLazyInternal(inst, "optout", (zod) => zod.def.out._zod.optout); - util.defineLazyInternal(inst, "propValues", (zod) => zod.def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}))); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - // prevent further checks - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - // Check if transform added any issues - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodPreprocess = /*@__PURE__*/ $constructor("$ZodPreprocess", (inst, def) => { - $ZodPipe.init(inst, def); -}); -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazyInternal(inst, "propValues", (zod) => zod.def.innerType._zod.propValues); - defineLazyInternal(inst, "values", (zod) => zod.def.innerType._zod.values); - defineLazyInternal(inst, "optin", (zod) => zod.def.innerType?._zod?.optin); - defineLazyInternal(inst, "optout", (zod) => zod.def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - // A repeat visit hands back a node that is still being built; freezing it here would make the rest of its keys fail to assign. - if (!payload.memo) - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - // is Zod schema - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || util.primitiveTypes.has(typeof part)) { - regexParts.push(util.escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "string", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}))); -const $ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - // Defined, not assigned: the classic prototype exposes `_def` as a getter with no setter. - Object.defineProperty(inst, "_def", { value: def }); - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - // Defined inline so the closure stays anonymous: binding it to a `const` first names it, which costs 256 bytes per implemented function. - return Object.defineProperty(function (...args) { - const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return Object.defineProperty(async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }, "_zod", { value: inst._zod, enumerable: false }); - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - // Check if output is a promise type to determine if we should use async implementation - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}))); -const $ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}))); -const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - // Cache the resolved inner type on the shared `def` so all clones of this lazy (e.g. via `.describe()`/`.meta()`) share the same inner instance, preserving identity for cycle detection on recursive schemas. - defineLazy(inst._zod, "innerType", () => { - const d = def; - if (!d._cachedInner) - d._cachedInner = def.getter(); - return d._cachedInner; - }); - defineLazyInternal(inst, "pattern", (zod) => zod.innerType?._zod?.pattern); - defineLazyInternal(inst, "propValues", (zod) => zod.innerType?._zod?.propValues); - defineLazyInternal(inst, "optin", (zod) => zod.innerType?._zod?.optin ?? undefined); - defineLazyInternal(inst, "optout", (zod) => zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -var registries_a; -const $output = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodOutput"))); -const $input = /*@__PURE__*/ (/* unused pure expression or super */ null && (Symbol("ZodInput"))); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registries_registry() { - return new $ZodRegistry(); -} -(registries_a = globalThis).__zod_globalRegistry ?? (registries_a.__zod_globalRegistry = registries_registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - - - - - -// @__NO_SIDE_EFFECTS__ -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link _cuid2} instead. - * See https://github.com/paralleldrive/cuid. - */ -// @__NO_SIDE_EFFECTS__ -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _creditCard(Class, params) { - return new Class({ - type: "string", - format: "credit_card", - check: "string_format", - abort: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = (/* unused pure expression or super */ null && ({ - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -})); -// @__NO_SIDE_EFFECTS__ -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_undefined(Class, params) { - return new Class({ - type: "undefined", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function api_null(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _any(Class) { - return new Class({ - type: "any", - }); -} -// @__NO_SIDE_EFFECTS__ -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -// @__NO_SIDE_EFFECTS__ -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _void(Class, params) { - return new Class({ - type: "void", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _date(Class, params) { - return new Class({ - type: "date", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _nan(Class, params) { - return new Class({ - type: "nan", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -// @__NO_SIDE_EFFECTS__ -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -// @__NO_SIDE_EFFECTS__ -function _positive(params) { - return _gt(0, params); -} -// negative -// @__NO_SIDE_EFFECTS__ -function _negative(params) { - return _lt(0, params); -} -// nonpositive -// @__NO_SIDE_EFFECTS__ -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -// @__NO_SIDE_EFFECTS__ -function _nonnegative(params) { - return _gte(0, params); -} -// @__NO_SIDE_EFFECTS__ -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxSize(maximum, params) { - return new checks.$ZodCheckMaxSize({ - check: "max_size", - ...util.normalizeParams(params), - maximum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _minSize(minimum, params) { - return new checks.$ZodCheckMinSize({ - check: "min_size", - ...util.normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _size(size, params) { - return new checks.$ZodCheckSizeEquals({ - check: "size_equals", - ...util.normalizeParams(params), - size, - }); -} -// @__NO_SIDE_EFFECTS__ -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -// @__NO_SIDE_EFFECTS__ -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -// @__NO_SIDE_EFFECTS__ -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -// @__NO_SIDE_EFFECTS__ -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -// @__NO_SIDE_EFFECTS__ -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -// @__NO_SIDE_EFFECTS__ -function _property(property, schema, params) { - return new checks.$ZodCheckProperty({ - check: "property", - property, - schema, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _properties(shape) { - return Object.entries(shape).map(([property, schema]) => new checks.$ZodCheckProperty({ check: "property", property, schema })); -} -// @__NO_SIDE_EFFECTS__ -function _mime(types, params) { - return new checks.$ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -// @__NO_SIDE_EFFECTS__ -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -// @__NO_SIDE_EFFECTS__ -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -// @__NO_SIDE_EFFECTS__ -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -// @__NO_SIDE_EFFECTS__ -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -// slugify -// @__NO_SIDE_EFFECTS__ -function _slugify() { - return _overwrite((input) => slugify(input)); -} -// @__NO_SIDE_EFFECTS__ -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...util.normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options: options, - discriminator, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -// @__NO_SIDE_EFFECTS__ -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof schemas.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _file(Class, params) { - return new Class({ - type: "file", - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -// @__NO_SIDE_EFFECTS__ -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : util.shallowClone(defaultValue); - }, - }); -} -// @__NO_SIDE_EFFECTS__ -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : util.constantCatch(catchValue)), - }); -} -// @__NO_SIDE_EFFECTS__ -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -// @__NO_SIDE_EFFECTS__ -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -// @__NO_SIDE_EFFECTS__ -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -// @__NO_SIDE_EFFECTS__ -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -// @__NO_SIDE_EFFECTS__ -function _custom(Class, fn, _params) { - const norm = util.normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// same as _custom but defaults to abort:false -// @__NO_SIDE_EFFECTS__ -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -// @__NO_SIDE_EFFECTS__ -function _superRefine(fn, params) { - const ch = _check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }, params); - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -// @__NO_SIDE_EFFECTS__ -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function api_meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -// @__NO_SIDE_EFFECTS__ -function _stringbool(Classes, _params) { - const params = util.normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? schemas.$ZodCodec; - const _Boolean = Classes.Boolean ?? schemas.$ZodBoolean; - const _String = Classes.String ?? schemas.$ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - codec._zod.bag.truthy = truthyArray; - codec._zod.bag.falsy = falsyArray; - codec._zod.bag.case = params.case ?? "insensitive"; - return codec; -} -// @__NO_SIDE_EFFECTS__ -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = util.normalizeParams(_params); - const def = { - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - - - -function assignProps(target, ...sources) { - for (const source of sources) { - for (const key of Reflect.ownKeys(source)) { - if (Object.prototype.propertyIsEnumerable.call(source, key)) { - assignProp(target, key, source[key]); - } - } - } - return target; -} -// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { -// return { -// processor: inputs.processor, -// metadataRegistry: inputs.metadata ?? globalRegistry, -// target: inputs.target ?? "draft-2020-12", -// unrepresentable: inputs.unrepresentable ?? "throw", -// }; -// } -function initializeContext(params) { - // Normalize target: convert old non-hyphenated versions to hyphenated versions - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - sharedDefsExtractedFor: undefined, - sharedEmitDoneFor: undefined, - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - intersections: [], - deferred: [], - external: params?.external ?? undefined, - }; -} -/** - * Applies the `unrepresentable` setting at a site that has no JSON Schema equivalent. Throws - * `message` unless the setting (or the handler's return value) says otherwise. Returns `true` if a - * custom JSON Schema was written into `json`, in which case the caller must not write its own. - */ -function handleUnrepresentable(schema, ctx, json, params, message) { - const result = typeof ctx.unrepresentable === "function" - ? ctx.unrepresentable({ zodSchema: schema, path: params.path, message }) - : ctx.unrepresentable; - if (result === "any") - return false; - if (result === undefined || result === "throw") - throw new Error(message); - Object.assign(json, result); - return true; -} -function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - // check for schema in seens - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - ctx.sharedDefsExtractedFor = undefined; - ctx.sharedEmitDoneFor = undefined; - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - const parent = schema._zod.parent; - if (parent) { - // Also set ref if processor didn't (for inheritance) - if (!result.ref) - result.ref = parent; - to_json_schema_process(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - } - // metadata - const meta = ctx.metadataRegistry.get(schema); - if (meta) - assignProps(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (ctx.io === "input" && "_prefault" in result.schema) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from ctx.seen in case it was overwritten - const _result = ctx.seen.get(schema); - return _result.schema; -} -// Escape a reference token for use in a JSON Pointer fragment (RFC 6901): `~` becomes `~0` and `/` becomes `~1`. The `~` replacement must run first. -function encodeJSONPointerSegment(segment) { - return segment.replace(/~/g, "~0").replace(/\//g, "~1"); -} -function extractDefs(ctx, schema -// params: EmitParams -) { - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // With `external` set, every registered schema resolves through the external branch of `makeURI`, so the root branch below produces the same ref the external branch would — this pass is identical whichever schema it is called with, and only needs to run once. - if (ctx.external && ctx.sharedDefsExtractedFor === ctx.external) - return; - // Track ids to detect duplicates across different schemas - const idToSchema = new Map(); - for (const entry of ctx.seen.entries()) { - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - const existing = idToSchema.get(id); - if (existing && existing !== entry[0]) { - throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`); - } - idToSchema.set(id, entry[0]); - } - } - // returns a ref to the schema defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes multiple schemas map to the same seen object. e.g. lazy - // external is configured - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; - // check if schema is in the external registry - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${encodeJSONPointerSegment(id)}` }; - } - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - // an id-less root has nowhere to be extracted to, so it stays inline and self-references as `#` - if (entry[1] === root && !entry[1].schema.id) { - return { ref: uriPrefix }; - } - // self-contained schema - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + encodeJSONPointerSegment(defId) }; - }; - // stored cached version in `def` property remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema or if the schema is the root schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } - if (ctx.external) - ctx.sharedDefsExtractedFor = ctx.external; -} -/** Rewrites `anyOf: [{type: "a"}, {type: "b"}]` to `type: ["a", "b"]`, which every JSON Schema draft treats as equivalent and most consumers render far better for the nullable case. Only branches that are a bare type assertion qualify — anything carrying a constraint, `$ref`, `const` or metadata is left alone. Runs after `flattenRef`, so a branch an override decorated or `$defs` extraction turned into a `$ref` is no longer bare and correctly stays in `anyOf`. `oneOf` is excluded: `integer` and `number` overlap, so "exactly one" and "at least one" are not the same there. OpenAPI 3.0 is excluded: its `type` must be a single string. */ -function compactTypeUnion(schema) { - const options = schema.anyOf; - if (!Array.isArray(options) || options.length === 0 || schema.type !== undefined) - return; - const types = []; - for (const option of options) { - if (!option || typeof option !== "object") - return; - // A branch that is itself a compactible union folds into this one — nested `anyOf` and a flat `type` array say the same thing. Compacting it first also makes the result independent of the order this pass walks the seen map in. - compactTypeUnion(option); - const keys = Object.keys(option); - if (keys.length !== 1 || keys[0] !== "type") - return; - const type = option.type; - for (const member of Array.isArray(type) ? type : [type]) { - if (typeof member !== "string") - return; - if (!types.includes(member)) - types.push(member); - } - } - delete schema.anyOf; - // A `type` array must be non-empty and unique (metaschema); a single member is spelled as a bare string. - schema.type = types.length === 1 ? types[0] : types; -} -/** Keywords `foldIntersection` knows how to combine. Anything else — `$ref`, `patternProperties`, - * an annotation like `description` — makes a member unfoldable, so a constraint this does not - * understand leaves the `allOf` alone instead of being silently dropped or misattributed. */ -const FOLDABLE_KEYS = new Set(["type", "properties", "required", "additionalProperties"]); -const UNION_KEYS = ["oneOf", "anyOf"]; -/** A member's constraint on a key it does not declare itself. A `catchall` states one; `false`, an absent `additionalProperties`, and the empty schema a loose object emits state nothing. */ -function undeclaredConstraint(member) { - const extra = member.additionalProperties; - if (extra === undefined || extra === false || typeof extra !== "object" || extra === null) - return null; - return Object.keys(extra).length ? extra : null; -} -/** Combines object members into the single object they describe together, or returns `null` if any of them carries a keyword outside {@link FOLDABLE_KEYS}. */ -function foldObjects(members) { - const objects = []; - for (const member of members) { - // A boolean subschema is legal JSON Schema and carries no keywords to fold. - if (typeof member !== "object" || member.type !== "object") - return null; - for (const key in member) { - if (!FOLDABLE_KEYS.has(key)) - return null; - } - objects.push(member); - } - const properties = {}; - const required = new Set(); - for (const object of objects) { - for (const key in object.properties) { - // `in` would report a `__proto__` key as already present via the prototype chain and skip it. - if (Object.prototype.hasOwnProperty.call(properties, key)) - continue; - // Every member constrains this key: the ones that declare it say how, and a `catchall` member constrains it too even though it does not name it. The key has to satisfy all of them, which is the same intersection one level down. - const parts = []; - for (const other of objects) { - const part = other.properties?.[key] ?? undeclaredConstraint(other); - if (part === null || part === undefined) - continue; - if (!parts.some((seen) => JSON.stringify(seen) === JSON.stringify(part))) - parts.push(part); - } - const merged = parts.length === 1 - ? parts[0] - : (foldObjects(parts) ?? { allOf: parts }); - assignProp(properties, key, merged); - } - for (const key of object.required ?? []) - required.add(key); - } - const folded = { type: "object", properties }; - if (required.size) - folded.required = [...required]; - // A key no member declares is rejected only when every member rejects it, so the fold is closed only when every member is. Otherwise it carries whatever the `catchall` members demand of such a key. - if (objects.every((object) => object.additionalProperties === false)) { - folded.additionalProperties = false; - } - else { - const constraints = []; - for (const object of objects) { - const constraint = undeclaredConstraint(object); - if (constraint && !constraints.some((seen) => JSON.stringify(seen) === JSON.stringify(constraint))) - constraints.push(constraint); - } - if (constraints.length === 1) - folded.additionalProperties = constraints[0]; - else if (constraints.length > 1) - folded.additionalProperties = { allOf: constraints }; - } - return folded; -} -/** `additionalProperties` in an `allOf` member sees only that member's own `properties`, so two - * closed object members reject each other's keys and the schema validates nothing. Zod's parser - * pools the key sets instead — `handleIntersectionResults` reports a key as unrecognized only when - * *every* side rejects it — so the emitted schema has to pool them too, and folding the members - * into one object is the encoding that says so on every target. - * - * This runs from `finalize`, after `extractDefs`, which is what keeps it clear of the `$ref` - * machinery: a member extracted into `$defs` is already a `$ref` by now and declines to fold, so it - * keeps its reference and its own closedness rather than being inlined as a stale copy. */ -function foldIntersection(json) { - const allOf = json.allOf; - if (!Array.isArray(allOf) || allOf.length < 2) - return; - // An `override` runs before this pass and may have written object keywords onto the intersection itself. Those are deliberate, so decline rather than overwrite them. - for (const key of FOLDABLE_KEYS) - if (key in json) - return; - // An intersection distributes over a union: `A & (X | Y)` is `(A & X) | (A & Y)`. Only the first union is distributed over; a second one stays among the members every branch folds against, where it fails the object check and declines the whole intersection rather than multiplying out. - const unions = allOf.filter((m) => UNION_KEYS.some((k) => Array.isArray(m[k]))); - let folded = null; - if (!unions.length) { - folded = foldObjects(allOf); - } - else { - const union = unions[0]; - const keyword = UNION_KEYS.find((k) => Array.isArray(union[k])); - if (Object.keys(union).length !== 1) - return; - const rest = allOf.filter((m) => m !== union); - const branches = union[keyword].map((branch) => foldObjects([...rest, branch])); - if (branches.some((b) => !b)) - return; - folded = { [keyword]: branches }; - } - if (!folded) - return; - delete json.allOf; - assignProps(json, folded); -} -function finalize(ctx, schema) { - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // flatten refs - inherit properties from parent schemas - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - // already processed - if (seen.ref === null) - return; - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - const ref = seen.ref; - seen.ref = null; // prevent infinite recursion - if (ref) { - flattenRef(ref); - const refSeen = ctx.seen.get(ref); - const refSchema = refSeen.schema; - // merge referenced schema into current - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - // older drafts can't combine $ref with other properties - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - assignProps(schema, refSchema); - } - // restore child's own properties (child wins) - assignProps(schema, _cached); - const isParentRef = zodSchema._zod.parent === ref; - // For parent chain, child is a refinement - remove parent-only properties - if (isParentRef) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (!(key in _cached)) { - delete schema[key]; - } - } - } - // When ref was extracted to $defs, remove properties that match the definition - if (refSchema.$ref && refSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in refSeen.def && JSON.stringify(schema[key]) === JSON.stringify(refSeen.def[key])) { - delete schema[key]; - } - } - } - } - // If parent was extracted (has $ref), propagate $ref to this schema. This handles cases like: readonly().meta({id}).describe() where processor sets ref to innerType but parent should be referenced - const parent = zodSchema._zod.parent; - if (parent && parent !== ref) { - // Ensure parent is processed first so its def has inherited properties - flattenRef(parent); - const parentSeen = ctx.seen.get(parent); - if (parentSeen?.schema.$ref) { - schema.$ref = parentSeen.schema.$ref; - // De-duplicate with parent's definition - if (parentSeen.def) { - for (const key in schema) { - if (key === "$ref" || key === "allOf") - continue; - if (key in parentSeen.def && JSON.stringify(schema[key]) === JSON.stringify(parentSeen.def[key])) { - delete schema[key]; - } - } - } - } - } - // execute overrides - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - // Flattening walks the whole map and clears each `ref` as it goes, so a second call over the same map is a no-op scan. Skip it outright once it has run for a registry conversion. - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - if (ctx.target !== "openapi-3.0") { - for (const entry of ctx.seen.entries()) { - compactTypeUnion(entry[1].def ?? entry[1].schema); - } - } - for (const rewrite of ctx.deferred) - rewrite(); - // After flattening, every member that was extracted is a `$ref`, so the fold sees the final shape. A schema that inherits an intersection — through `z.lazy`, or any `ref` chain — holds the same `allOf` array, so fold by array identity to catch every copy. - if (ctx.intersections.length) { - const carriers = new Map(); - for (const seen of ctx.seen.values()) { - for (const json of [seen.schema, seen.def]) { - const allOf = json?.allOf; - if (!Array.isArray(allOf)) - continue; - const existing = carriers.get(allOf); - if (existing) - existing.push(json); - else - carriers.set(allOf, [json]); - } - } - for (const allOf of ctx.intersections) { - for (const json of carriers.get(allOf) ?? []) - foldIntersection(json); - } - } - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") { - // OpenAPI 3.0 schema objects should not include a $schema property - } - else { - // Arbitrary string values are allowed but won't have a $schema property set - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - // when the root was extracted into $defs, `root.schema` is the `$ref` wrapper and `root.def` is the body that now lives under $defs - assignProps(result, root.defId ? root.schema : (root.def ?? root.schema)); - // The `id` in `.meta()` is a Zod-specific registration tag used to extract schemas into $defs — it is not user-facing JSON Schema metadata. Strip it from the output body where it would otherwise leak. The id is preserved implicitly via the $defs key (and via $ref paths). - const rootMetaId = ctx.metadataRegistry.get(schema)?.id; - if (rootMetaId !== undefined && result.id === rootMetaId) - delete result.id; - // build defs object. With `external`, `defs` is the shared object every schema writes into, so the same entries are reassigned on every call. Without it, `defs` is fresh per call and must be rebuilt. - const defs = ctx.external?.defs ?? {}; - if (!ctx.external || ctx.sharedEmitDoneFor !== ctx.external) { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - if (seen.def.id === seen.defId) - delete seen.def.id; - assignProp(defs, seen.defId, seen.def); - } - } - } - if (ctx.external) - ctx.sharedEmitDoneFor = ctx.external; - // set definitions in result - if (ctx.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed each call to finalize() is functionally independent though the seen map is shared - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input", ctx.processors), - output: createStandardJSONSchemaMethod(schema, "output", ctx.processors), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault" || - def.type === "catch") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - if (_schema._zod.traits.has("$ZodCodec")) - return true; - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -/** - * Creates a toJSONSchema method for a schema instance. - * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. - */ -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - - - - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set -}; -// ==================== SIMPLE TYPE PROCESSORS ==================== -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding, laxFormat } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - // `z.iso.time()` is never full-time, and `laxFormat` carries the datetime shapes that also accept what their keyword forbids - if (format === "time" || laxFormat) { - delete json.format; - } - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const patternList = [...patterns]; - if (patternList.length === 1) - json.pattern = patternList[0].source; - else if (patternList.length > 1) { - json.allOf = [ - ...patternList.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - // when both minimum and exclusiveMinimum exist, pick the more restrictive one - const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY); - const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY); - const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0"; - if (exMin) { - if (legacy) { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - else if (typeof minimum === "number") { - json.minimum = minimum; - } - if (exMax) { - if (legacy) { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - else if (typeof maximum === "number") { - json.maximum = maximum; - } - if (typeof multipleOf === "number") { - // JSON Schema requires a divisor strictly greater than zero, and a non-finite one does not survive JSON at all. A negative divisor accepts exactly what its absolute value accepts, so it still maps; zero, NaN and Infinity have no keyword form. - if (Number.isFinite(multipleOf) && multipleOf !== 0) - json.multipleOf = Math.abs(multipleOf); - else - handleUnrepresentable(schema, ctx, json, params, `A multipleOf divisor of ${multipleOf} cannot be represented in JSON Schema`); - } -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "BigInt cannot be represented in JSON Schema"); -}; -const symbolProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Symbols cannot be represented in JSON Schema"); -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Undefined cannot be represented in JSON Schema"); -}; -const voidProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Void cannot be represented in JSON Schema"); -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const dateProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Date cannot be represented in JSON Schema"); -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - // an empty enum accepts nothing, same as z.never() - if (values.length === 0) { - json.not = {}; - return; - } - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // a literal with no values accepts nothing, same as z.never() - if (def.values.length === 0) { - json.not = {}; - return; - } - const vals = []; - for (const val of def.values) { - if (val === undefined) { - // a custom schema replaces the whole literal, so there is nothing left to accumulate - if (handleUnrepresentable(schema, ctx, json, params, "Literal `undefined` cannot be represented in JSON Schema")) - return; - // otherwise do not add to vals - } - else if (typeof val === "bigint") { - if (handleUnrepresentable(schema, ctx, json, params, "BigInt literals cannot be represented in JSON Schema")) - return; - vals.push(Number(val)); - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "NaN cannot be represented in JSON Schema"); -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - Object.assign(_json, file); // shared props at root - _json.anyOf = mime.map((m) => ({ contentMediaType: m })); // only contentMediaType differs - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Custom types cannot be represented in JSON Schema"); -}; -const functionProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Function types cannot be represented in JSON Schema"); -}; -const transformProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Transforms cannot be represented in JSON Schema"); -}; -const mapProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Map cannot be represented in JSON Schema"); -}; -const setProcessor = (schema, ctx, json, params) => { - handleUnrepresentable(schema, ctx, json, params, "Set cannot be represented in JSON Schema"); -}; -// ==================== COMPOSITE TYPE PROCESSORS ==================== -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = to_json_schema_process(def.element, ctx, { - ...params, - path: [...params.path, "items"], - }); -}; -// Transform and catch set `optin = "optional"` at runtime so the parser lets them observe an -// absent key, but their declared input type stays required. An input JSON Schema describes the -// declared type, so resolve past them to the schema that actually carries the optionality. -// Used by both `objectProcessor` (for `required`) and `tupleProcessor` (for `minItems`); see -// wiki/optionality.md, "The JSON Schema emitter reads the *static* value". -function inputOptin(schema) { - const def = schema._zod.def; - if (def.type === "pipe" && def.in._zod.traits.has("$ZodTransform")) { - return inputOptin(def.out); - } - if (def.type === "catch") { - return inputOptin(def.innerType); - } - return schema._zod.optin; -} -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const shape = def.shape; - // dropping it while still emitting `additionalProperties: false` would emit a schema that rejects data this one requires - const symbolKeys = Object.getOwnPropertySymbols(shape); - if (symbolKeys.length && - handleUnrepresentable(schema, ctx, json, params, "Symbol keys cannot be represented in JSON Schema")) { - return; - } - json.type = "object"; - json.properties = {}; - for (const key in shape) { - // assignProp so a __proto__ key becomes an own property instead of hitting the inherited setter on the plain {} we build into - assignProp(json.properties, key, to_json_schema_process(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - })); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const field = def.shape[key]; - if (ctx.io === "input") { - return inputOptin(field) === undefined; - } - else { - return field._zod.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = to_json_schema_process(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches). This includes both z.xor() and discriminated unions - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = to_json_schema_process(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = to_json_schema_process(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; - // Recorded innermost first, so a nested intersection has already folded by the time this one is considered. The array is the handle rather than the schema, because a wrapper that inherits this schema shares the same array; `finalize` folds every object holding it. See `foldIntersection`. - ctx.intersections.push(allOf); -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? to_json_schema_process(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - let minItems = def.items.length; - while (minItems > 0) { - const item = def.items[minItems - 1]; - const optional = ctx.io === "input" ? inputOptin(item) !== undefined : item._zod.optout === "optional"; - if (!optional) - break; - minItems--; - } - const maxItems = def.items.length; - const isClosed = !def.rest; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (isClosed) { - json.items = false; - } - else if (rest) { - json.items = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - else { - json.items = prefixItems; - if (isClosed) { - json.additionalItems = false; - } - else if (rest) { - json.additionalItems = rest; - } - if (minItems > 0) - json.minItems = minItems; - if (isClosed) - json.maxItems = maxItems; - } - // explicit user-defined length checks take precedence - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -/** JSON object keys are always strings, so a numeric record key schema is re-expressed over the - * numeric-string form the record parser matches. Deferred to `finalize`, after the flatten: a key - * behind a wrapper only carries its own `type` before then, and a union key only has its branches. - * - * A numeric bound cannot apply to a property name, so `minimum` and its siblings are dropped rather - * than carried over: keeping them beside `type: "string"` reproduces the match-nothing schema this - * exists to fix. A key that carries one therefore emits wider than the record parses — `z.record(z.number().min(5), V)` - * accepts `"3"` — which is the deliberate trade, since throwing on it would reject an ordinary schema - * outright. */ -function stringifyKeyNames(bySchema, json, visited) { - // an extracted key that rewrites cannot go on sharing its definition — the string form a key position needs is not the number form every other reference wants — so it inlines. One that does not rewrite keeps the `$ref`. - if (json.$ref) { - // a recursive key holds its own reference inside its definition, so a node already on the path is left alone rather than resolved again - if (visited.has(json)) - return json; - visited.add(json); - const def = bySchema.get(json)?.def; - if (!def) - return json; - const inlined = stringifyKeyNames(bySchema, def, visited); - return inlined === def ? json : inlined; - } - for (const keyword of ["anyOf", "oneOf"]) { - const branches = json[keyword]; - if (!Array.isArray(branches)) - continue; - const mapped = branches.map((branch) => stringifyKeyNames(bySchema, branch, visited)); - // rebuilding regardless would detach a key that had nothing to re-express, dropping its `$ref` and leaking the internal `id` - if (mapped.some((branch, i) => branch !== branches[i])) - json = { ...json, [keyword]: mapped }; - } - // a member that already admits a string leaves the key unconstrained, so the node's own type re-expresses only when every member is numeric - const types = Array.isArray(json.type) ? json.type : [json.type]; - const numericType = !types.includes("string") && types.some((t) => t === "number" || t === "integer"); - // a heterogeneous key carries no type at all, so its numeric members are caught here instead - const values = json.enum ?? (json.const !== undefined ? [json.const] : undefined); - if (!numericType && !values?.some((v) => typeof v === "number")) - return json; - const { minimum, maximum, exclusiveMinimum, exclusiveMaximum, multipleOf, format, id, ...rest } = json; - if (rest.enum) - rest.enum = rest.enum.map((v) => (typeof v === "number" ? String(v) : v)); - else if (typeof rest.const === "number") - rest.const = String(rest.const); - // a heterogeneous key keeps its absent type: the stringified members already say what a key may be - if (!numericType) - return rest; - rest.type = "string"; - if (!values) - rest.pattern = (types.includes("number") ? number : integer).source; - return rest; -} -/** Every record of one conversion, so the carriers are found in a single pass rather than once per record. */ -const pendingRecords = new WeakMap(); -function rewriteKeyNames(ctx) { - // an extracted key is resolved by the object `extractToDef` left in its place, so the map is built once rather than searched per reference. `_zod.toJSONSchema` can hand the same object to two schemas, so the first entry carrying a body wins, as a search would have found it. - const bySchema = new Map(); - for (const entry of ctx.seen.values()) { - if (entry.def && !bySchema.has(entry.schema)) - bySchema.set(entry.schema, entry); - } - const rewrites = new Map(); - for (const record of pendingRecords.get(ctx) ?? []) { - const seen = ctx.seen.get(record); - const names = (seen?.def ?? seen?.schema)?.propertyNames; - if (!names || names === true || rewrites.has(names)) - continue; - const rewritten = stringifyKeyNames(bySchema, names, new Set()); - if (rewritten !== names) - rewrites.set(names, rewritten); - } - if (!rewrites.size) - return; - // the flatten has already copied each record's own properties onto every wrapper by reference, and an extracted body is another such copy, so every carrier holding a rewritten key is updated together - for (const entry of ctx.seen.values()) { - for (const carrier of [entry.schema, entry.def]) { - const rewritten = carrier && rewrites.get(carrier.propertyNames); - if (rewritten) - carrier.propertyNames = rewritten; - } - } -} -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - // For looseRecord with regex patterns, use patternProperties. This correctly represents "only validate keys matching the pattern" semantics and composes well with allOf (intersections) - const keyType = def.keyType; - const keyBag = keyType._zod.bag; - const patterns = keyBag?.patterns; - if (def.mode === "loose" && patterns && patterns.size > 0) { - // Use patternProperties for looseRecord with regex patterns - const valueSchema = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "patternProperties", "*"], - }); - json.patternProperties = {}; - for (const pattern of patterns) { - assignProp(json.patternProperties, pattern.source, valueSchema); - } - } - else { - // Default behavior: use propertyNames + additionalProperties - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = to_json_schema_process(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - let pending = pendingRecords.get(ctx); - if (!pending) { - pending = []; - pendingRecords.set(ctx, pending); - ctx.deferred.push(() => rewriteKeyNames(ctx)); - } - pending.push(schema); - } - json.additionalProperties = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } - // Add required for keys with discrete values (enum, literal, etc.) - const keyValues = keyType._zod.values; - // Every key shares one value schema, so an optional-in value makes the whole key set omittable on input. Output keeps them: the exhaustive branch assigns every key, even one whose value came back undefined. - const omittableOnInput = ctx.io === "input" && inputOptin(def.valueType) !== undefined; - if (keyValues && !def.partial && !omittableOnInput) { - const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number"); - if (validKeyValues.length > 0) { - json.required = validKeyValues.map(String); - } - } -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -/** Round-trips a default value through JSON so the emitted schema is guaranteed to be valid JSON. - * A BigInt has no reliable encoding, so it goes through `unrepresentable` like any other - * unrepresentable value. Returns a sentinel when the caller must not write a default of its own. */ -const UNREPRESENTABLE_DEFAULT = Symbol(); -function serializeDefaultValue(value, schema, ctx, json, params) { - let unrepresentable = false; - const serialized = JSON.stringify(value, (_, val) => { - if (typeof val !== "bigint") - return val; - unrepresentable = true; - return null; - }); - if (!unrepresentable) - return JSON.parse(serialized); - handleUnrepresentable(schema, ctx, json, params, "BigInt defaults cannot be represented in JSON Schema"); - return UNREPRESENTABLE_DEFAULT; -} -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json.default = value; -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io !== "input") - return; - const value = serializeDefaultValue(def.defaultValue, schema, ctx, json, params); - if (value !== UNREPRESENTABLE_DEFAULT) - json._prefault = value; -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - handleUnrepresentable(schema, ctx, json, params, "Dynamic catch values are not supported in JSON Schema"); - return; - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const inIsTransform = def.in._zod.traits.has("$ZodTransform"); - const innerType = ctx.io === "input" ? (inIsTransform ? def.out : def.in) : def.out; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -// ==================== ALL PROCESSORS ==================== -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - // Registry case - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - // First pass: process all schemas to build the seen map - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - to_json_schema_process(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - // Update the context with external configuration - ctx.external = external; - // Second pass: emit each schema - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - assignProp(schemas, key, finalize(ctx, schema)); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - // Single schema case - const ctx = initializeContext({ ...params, processors: allProcessors }); - to_json_schema_process(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - - -const en_error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - map: { unit: "entries", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const FormatDictionary = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - mac: "MAC address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - credit_card: "credit card number", - jwt: "JWT", - template_literal: "input", - }; - // type names: missing keys = do not translate (use raw value via ?? fallback) - const TypeDictionary = { - // Compatibility: "nan" -> "NaN" for display - nan: "NaN", - // All other type names omitted - they fall back to raw values via ?? operator - }; - function getTypeName(type, input) { - if (type === "number" && typeof input === "number" && !Number.isFinite(input)) { - return String(input); - } - return TypeDictionary[type] ?? type; - } - return (issue) => { - switch (issue.code) { - case "invalid_type": { - const expected = getTypeName(issue.expected); - const receivedType = parsedType(issue.input); - const received = getTypeName(receivedType, issue.input); - return `Invalid input: expected ${expected}, received ${received}`; - } - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.exact ? "exactly " : issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.exact ? "exactly " : issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${FormatDictionary[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - if (issue.options && Array.isArray(issue.options) && issue.options.length > 0) { - const opts = issue.options.map((o) => `'${o}'`).join(" | "); - return `Invalid discriminator value. Expected ${opts}`; - } - if (issue.inclusive === false) { - return "Invalid input: more than one option matched"; - } - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -/* export default */ function en() { - return { - localeError: en_error(), - }; -} - - - - -/* Prototypes that already carry the lazy helper methods. Seeded with the - * intrinsics so that `init` on a foreign object — it accepts any object — - * can never install an accessor onto a prototype we do not own. */ -const _installedErrorProtos = /* @__PURE__ */ new WeakSet([Object.prototype, Error.prototype]); -/* Helper methods live as non-enumerable lazy getters on the shared - * prototype instead of own properties on every instance. On first - * access the getter allocates the per-instance closure and caches it - * as a non-enumerable own property, so detached usage still works and - * the allocation only happens for methods actually touched. */ -function _lazyMethod(proto, key, make) { - Object.defineProperty(proto, key, { - configurable: true, - enumerable: false, - get() { - const value = make(this); - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - return value; - }, - set(value) { - Object.defineProperty(this, key, { value, configurable: true, writable: true }); - }, - }); -} -const classic_errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - const proto = Object.getPrototypeOf(inst); - if (_installedErrorProtos.has(proto)) - return; - _installedErrorProtos.add(proto); - _lazyMethod(proto, "format", (self) => (mapper) => formatError(self, mapper)); - _lazyMethod(proto, "flatten", (self) => (mapper) => flattenError(self, mapper)); - _lazyMethod(proto, "addIssue", (self) => (issue) => { - self.issues.push(issue); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - _lazyMethod(proto, "addIssues", (self) => (issues) => { - self.issues.push(...issues); - self.message = JSON.stringify(self.issues, jsonStringifyReplacer, 2); - }); - Object.defineProperty(proto, "isEmpty", { - configurable: true, - enumerable: false, - get() { - return this.issues.length === 0; - }, - }); -}; -const ZodError = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodError", classic_errors_initializer))); -const ZodRealError = /*@__PURE__*/ $constructor("ZodError", classic_errors_initializer, undefined, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - - - -const classic_parse_parse = /* @__PURE__ */ parse_parse(ZodRealError); -const classic_parse_parseAsync = /* @__PURE__ */ parse_parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); - -// Codec functions -const classic_parse_encode = /* @__PURE__ */ parse_encode(ZodRealError); -const classic_parse_decode = /* @__PURE__ */ parse_decode(ZodRealError); -const classic_parse_encodeAsync = /* @__PURE__ */ parse_encodeAsync(ZodRealError); -const classic_parse_decodeAsync = /* @__PURE__ */ parse_decodeAsync(ZodRealError); -const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - - - - - - - - -// Register English as the default locale on first ZodType construction. Hooked into the `ZodType` `$constructor` (rather than a top-level `config(en())` in `external.ts`) so bundlers honoring `sideEffects: false` can't tree-shake it out — see #5953, #5725. An explicit `z.config(z.locales.xx())` call wins regardless of order, since this only sets the default when none is present. -function _ensureDefaultLocale() { - if (!globalConfig.localeError) - core_config(en()); -} -// the default memoizer is read by the core container init, which runs before `ZodType.init`, so each container calls this first -function _ensureDefaultMemoizer() { - if (!globalConfig.memoizer) - core_config({ memoizer: memoizer() }); -} -const ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - _ensureDefaultLocale(); - $ZodType.init(inst, def); - inst.def = def; - inst.type = def.type; - return inst; -}, { - check(...chks) { - const def = this.def; - return this.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - }), { parent: true }); - }, - with(...chks) { - return this.check(...chks); - }, - clone(def, params) { - return clone(this, def, params); - }, - brand() { - return this; - }, - register(reg, meta) { - reg.add(this, meta); - return this; - }, - refine(check, params) { - return this.check(refine(check, params)); - }, - superRefine(refinement, params) { - return this.check(superRefine(refinement, params)); - }, - overwrite(fn) { - return this.check(_overwrite(fn)); - }, - optional() { - return schemas_optional(this); - }, - exactOptional() { - return exactOptional(this); - }, - nullable() { - return nullable(this); - }, - nullish() { - return schemas_optional(nullable(this)); - }, - nonoptional(params) { - return nonoptional(this, params); - }, - array() { - return schemas_array(this); - }, - or(arg) { - return schemas_union([this, arg]); - }, - and(arg) { - return intersection(this, arg); - }, - transform(tx) { - return pipe(this, transform(tx)); - }, - default(d) { - return schemas_default(this, d); - }, - prefault(d) { - return prefault(this, d); - }, - catch(params) { - return schemas_catch(this, params); - }, - pipe(target) { - return pipe(this, target); - }, - readonly() { - return readonly(this); - }, - describe(description) { - const cl = this.clone(); - globalRegistry.add(cl, { description }); - return cl; - }, - meta(...args) { - // overloaded: meta() returns the registered metadata, meta(data) returns a clone with `data` registered. The mapped type picks up the second overload, so we accept variadic any-args and return `any` to satisfy both at runtime. - if (args.length === 0) - return globalRegistry.get(this); - const cl = this.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }, - isOptional() { - return this.safeParse(undefined).success; - }, - isNullable() { - return this.safeParse(null).success; - }, - apply(fn, ...args) { - return args.length === 0 ? fn(this) : fn(this, ...args); - }, - // Overrides core's `~standard` to add `jsonSchema`. Must stay a prototype entry: redefining it per instance demotes instances to dictionary mode. - get "~standard"() { - return hide(this, "~standard", { - ...standardProps(this), - jsonSchema: { - input: createStandardJSONSchemaMethod(this, "input"), - output: createStandardJSONSchemaMethod(this, "output"), - }, - }); - }, - set "~standard"(value) { - util_own(this, "~standard", value); - }, - parse: function _parse(data, params) { - return classic_parse_parse(this, data, params, { callee: _parse }); - }, - parseAsync: async function _parseAsync(data, params) { - return await classic_parse_parseAsync(this, data, params, { callee: _parseAsync }); - }, - safeParse(data, params) { - return parse_safeParse(this, data, params); - }, - async safeParseAsync(data, params) { - return parse_safeParseAsync(this, data, params); - }, - // `spa` is an alias: same function object as `safeParseAsync`, as before. - get spa() { - return this?.safeParseAsync; - }, - set spa(value) { - util_own(this, "spa", value); - }, - encode: function _encode(data, params) { - return classic_parse_encode(this, data, params, { callee: _encode }); - }, - decode: function _decode(data, params) { - return classic_parse_decode(this, data, params, { callee: _decode }); - }, - encodeAsync: async function _encodeAsync(data, params) { - return await classic_parse_encodeAsync(this, data, params, { callee: _encodeAsync }); - }, - decodeAsync: async function _decodeAsync(data, params) { - return await classic_parse_decodeAsync(this, data, params, { callee: _decodeAsync }); - }, - safeEncode(data, params) { - return parse_safeEncode(this, data, params); - }, - safeDecode(data, params) { - return parse_safeDecode(this, data, params); - }, - async safeEncodeAsync(data, params) { - return parse_safeEncodeAsync(this, data, params); - }, - async safeDecodeAsync(data, params) { - return parse_safeDecodeAsync(this, data, params); - }, - toJSONSchema(params) { - return createToJSONSchemaMethod(this, {})(params); - }, - // Reads through to the registry on every access, so it must not cache. - get description() { - return globalRegistry.get(this)?.description; - }, - // No setter: `schema._def = x` throws, as it did when `_def` was a non-writable own property. - get _def() { - return this._zod.def; - }, -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; -}, { - regex(...args) { - return this.check(_regex(...args)); - }, - includes(...args) { - return this.check(_includes(...args)); - }, - startsWith(...args) { - return this.check(_startsWith(...args)); - }, - endsWith(...args) { - return this.check(_endsWith(...args)); - }, - min(...args) { - return this.check(_minLength(...args)); - }, - max(...args) { - return this.check(_maxLength(...args)); - }, - length(...args) { - return this.check(_length(...args)); - }, - nonempty(...args) { - return this.check(_minLength(1, ...args)); - }, - lowercase(params) { - return this.check(_lowercase(params)); - }, - uppercase(params) { - return this.check(_uppercase(params)); - }, - trim() { - return this.check(_trim()); - }, - normalize(...args) { - return this.check(_normalize(...args)); - }, - toLowerCase() { - return this.check(_toLowerCase()); - }, - toUpperCase() { - return this.check(_toUpperCase()); - }, - slugify() { - return this.check(_slugify()); - }, -}); -const ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); -}, { - email(params) { - return this.check(_email(ZodEmail, params)); - }, - url(params) { - return this.check(_url(ZodURL, params)); - }, - jwt(params) { - return this.check(_jwt(ZodJWT, params)); - }, - emoji(params) { - return this.check(api_emoji(ZodEmoji, params)); - }, - guid(params) { - return this.check(_guid(ZodGUID, params)); - }, - uuid(params) { - return this.check(_uuid(ZodUUID, params)); - }, - uuidv4(params) { - return this.check(_uuidv4(ZodUUID, params)); - }, - uuidv6(params) { - return this.check(_uuidv6(ZodUUID, params)); - }, - uuidv7(params) { - return this.check(_uuidv7(ZodUUID, params)); - }, - nanoid(params) { - return this.check(_nanoid(ZodNanoID, params)); - }, - cuid(params) { - return this.check(_cuid(ZodCUID, params)); - }, - cuid2(params) { - return this.check(_cuid2(ZodCUID2, params)); - }, - ulid(params) { - return this.check(_ulid(ZodULID, params)); - }, - base64(params) { - return this.check(_base64(ZodBase64, params)); - }, - base64url(params) { - return this.check(_base64url(ZodBase64URL, params)); - }, - xid(params) { - return this.check(_xid(ZodXID, params)); - }, - ksuid(params) { - return this.check(_ksuid(ZodKSUID, params)); - }, - ipv4(params) { - return this.check(_ipv4(ZodIPv4, params)); - }, - ipv6(params) { - return this.check(_ipv6(ZodIPv6, params)); - }, - cidrv4(params) { - return this.check(_cidrv4(ZodCIDRv4, params)); - }, - cidrv6(params) { - return this.check(_cidrv6(ZodCIDRv6, params)); - }, - e164(params) { - return this.check(_e164(ZodE164, params)); - }, - datetime(params) { - return this.check(_isoDateTime(ZodISODateTime, params)); - }, - date(params) { - return this.check(_isoDate(ZodISODate, params)); - }, - time(params) { - return this.check(_isoTime(schemas_ZodISOTime, params)); - }, - duration(params) { - return this.check(_isoDuration(schemas_ZodISODuration, params)); - }, -}); -function schemas_string(params) { - return _string(ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const schemas_ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_guid(params) { - return core._guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_uuid(params) { - return core._uuid(ZodUUID, params); -} -function uuidv4(params) { - return core._uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return core._uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function uuidv7(params) { - return core._uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return core._url(ZodURL, { - protocol: core.regexes.httpProtocol, - hostname: core.regexes.domain, - ...util.normalizeParams(params), - }); -} -const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_emoji(params) { - return core._emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_nanoid(params) { - return core._nanoid(ZodNanoID, params); -} -/** - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link ZodCUID2} instead. - * See https://github.com/paralleldrive/cuid. - */ -const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -/** - * Validates a CUID v1 string. - * - * @deprecated CUID v1 is deprecated by its authors due to information leakage - * (timestamps embedded in the id). Use {@link cuid2 | `z.cuid2()`} instead. - * See https://github.com/paralleldrive/cuid. - */ -function schemas_cuid(params) { - return core._cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid2(params) { - return core._cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ulid(params) { - return core._ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_xid(params) { - return core._xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ksuid(params) { - return core._ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv4(params) { - return core._ipv4(ZodIPv4, params); -} -const ZodMAC = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMAC", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_mac(params) { - return core._mac(ZodMAC, params); -} -const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv6(params) { - return core._ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv4(params) { - return core._cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv6(params) { - return core._cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64(params) { - return core._base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64url(params) { - return core._base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_e164(params) { - return core._e164(ZodE164, params); -} -const ZodCreditCard = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCreditCard", (inst, def) => { - core.$ZodCreditCard.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function schemas_creditCard(params) { - return core._creditCard(ZodCreditCard, params); -} -const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return core._jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - core.$ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}))); -function stringFormat(format, fnOrRegex, _params = {}) { - return core._stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function schemas_hostname(_params) { - return core._stringFormat(ZodCustomStringFormat, "hostname", core.regexes.hostname, _params); -} -function schemas_hex(_params) { - return core._stringFormat(ZodCustomStringFormat, "hex", core.regexes.hex, _params); -} -function schemas_hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = core.regexes[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return core._stringFormat(ZodCustomStringFormat, format, regex, params); -} -const ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}, { - gt(value, params) { - return this.check(_gt(value, params)); - }, - gte(value, params) { - return this.check(_gte(value, params)); - }, - min(value, params) { - return this.check(_gte(value, params)); - }, - lt(value, params) { - return this.check(_lt(value, params)); - }, - lte(value, params) { - return this.check(_lte(value, params)); - }, - max(value, params) { - return this.check(_lte(value, params)); - }, - int(params) { - return this.check(schemas_int(params)); - }, - safe(params) { - return this.check(schemas_int(params)); - }, - positive(params) { - return this.check(_gt(0, params)); - }, - nonnegative(params) { - return this.check(_gte(0, params)); - }, - negative(params) { - return this.check(_lt(0, params)); - }, - nonpositive(params) { - return this.check(_lte(0, params)); - }, - multipleOf(value, params) { - return this.check(_multipleOf(value, params)); - }, - step(value, params) { - return this.check(_multipleOf(value, params)); - }, - finite() { - return this; - }, -}); -function schemas_number(params) { - return _number(ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - ZodNumber.init(inst, def); -}); -function schemas_int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return core._float32(ZodNumberFormat, params); -} -function float64(params) { - return core._float64(ZodNumberFormat, params); -} -function int32(params) { - return core._int32(ZodNumberFormat, params); -} -function uint32(params) { - return core._uint32(ZodNumberFormat, params); -} -const ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function schemas_boolean(params) { - return _boolean(ZodBoolean, params); -} -const ZodBigInt = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigInt", (inst, def) => { - core.$ZodBigInt.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.bigintProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}, { - gte(value, params) { - return this.check(checks.gte(value, params)); - }, - min(value, params) { - return this.check(checks.gte(value, params)); - }, - gt(value, params) { - return this.check(checks.gt(value, params)); - }, - lt(value, params) { - return this.check(checks.lt(value, params)); - }, - lte(value, params) { - return this.check(checks.lte(value, params)); - }, - max(value, params) { - return this.check(checks.lte(value, params)); - }, - positive(params) { - return this.check(checks.gt(BigInt(0), params)); - }, - negative(params) { - return this.check(checks.lt(BigInt(0), params)); - }, - nonpositive(params) { - return this.check(checks.lte(BigInt(0), params)); - }, - nonnegative(params) { - return this.check(checks.gte(BigInt(0), params)); - }, - multipleOf(value, params) { - return this.check(checks.multipleOf(value, params)); - }, -}))); -function schemas_bigint(params) { - return core._bigint(ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodBigIntFormat", (inst, def) => { - core.$ZodBigIntFormat.init(inst, def); - ZodBigInt.init(inst, def); -}))); -function int64(params) { - return core._int64(ZodBigIntFormat, params); -} -function uint64(params) { - return core._uint64(ZodBigIntFormat, params); -} -const ZodSymbol = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSymbol", (inst, def) => { - core.$ZodSymbol.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.symbolProcessor(inst, ctx, json, params); -}))); -function symbol(params) { - return core._symbol(ZodSymbol, params); -} -const ZodUndefined = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodUndefined", (inst, def) => { - core.$ZodUndefined.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.undefinedProcessor(inst, ctx, json, params); -}))); -function schemas_undefined(params) { - return core._undefined(ZodUndefined, params); -} - -const ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function schemas_null(params) { - return api_null(ZodNull, params); -} - -const ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); -}); -function any() { - return _any(ZodAny); -} -const ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); -}); -function unknown() { - return _unknown(ZodUnknown); -} -const ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function never(params) { - return _never(ZodNever, params); -} -const ZodVoid = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodVoid", (inst, def) => { - core.$ZodVoid.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.voidProcessor(inst, ctx, json, params); -}))); -function schemas_void(params) { - return core._void(ZodVoid, params); -} - -const ZodDate = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodDate", (inst, def) => { - core.$ZodDate.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.dateProcessor(inst, ctx, json, params); - inst.min = (value, params) => inst.check(checks.gte(value, params)); - inst.max = (value, params) => inst.check(checks.lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}))); -function schemas_date(params) { - return core._date(ZodDate, params); -} -const ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodArray.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; -}, { - min(n, params) { - return this.check(_minLength(n, params)); - }, - nonempty(params) { - return this.check(_minLength(1, params)); - }, - max(n, params) { - return this.check(_maxLength(n, params)); - }, - length(n, params) { - return this.check(_length(n, params)); - }, - unwrap() { - return this.element; - }, -}); -function schemas_array(element, params) { - return _array(ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return schemas_enum(Object.keys(shape)); -} -const ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodObjectJIT.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - installLazyProp(inst, "shape", (self) => self._zod.def.shape, false); -}, { - keyof() { - return schemas_enum(Object.keys(this._zod.def.shape)); - }, - catchall(catchall) { - return this.clone({ ...this._zod.def, catchall: catchall }); - }, - passthrough() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - loose() { - return this.clone({ ...this._zod.def, catchall: unknown() }); - }, - strict() { - return this.clone({ ...this._zod.def, catchall: never() }); - }, - strip() { - return this.clone({ ...this._zod.def, catchall: undefined }); - }, - extend(incoming) { - return extend(this, incoming); - }, - safeExtend(incoming) { - return safeExtend(this, incoming); - }, - merge(other) { - return merge(this, other); - }, - pick(mask) { - return pick(this, mask); - }, - omit(mask) { - return omit(this, mask); - }, - partial(...args) { - return partial(ZodOptional, this, args[0]); - }, - exactPartial(...args) { - return partial(ZodExactOptional, this, args[0], "exactPartial"); - }, - required(...args) { - return util_required(ZodNonOptional, this, args[0]); - }, -}); -function schemas_object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: never(), - ...util.normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function schemas_union(options, params) { - return new ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodXor", (inst, def) => { - ZodUnion.init(inst, def); - core.$ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}))); -/** Creates an exclusive union (XOR) where exactly one option must match. - * Unlike regular unions that succeed when any option matches, xor fails if - * zero or more than one option matches the input. */ -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...util.normalizeParams(params), - }); -} -const ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new ZodDiscriminatedUnion({ - type: "union", - options: options, - discriminator, - ...normalizeParams(params), - }); -} -const ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const ZodTuple = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTuple", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodTuple.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.tupleProcessor(inst, ctx, json, params); -}, { - rest(rest) { - return this.clone({ - ...this._zod.def, - rest: rest, - }); - }, - partial() { - const def = this._zod.def; - // a refinement was authored against the full arity; partialing would run it on a shorter array - if (def.checks?.length) - throw new Error(".partial() cannot be used on tuple schemas containing refinements"); - return this.clone({ - ...def, - items: def.items.map((item) => new ZodOptional({ type: "optional", innerType: item })), - }); - }, -}))); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof core.$ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new ZodTuple({ - type: "tuple", - items: items, - rest, - ...util.normalizeParams(params), - }); -} -const ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodRecord.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function schemas_record(keyType, valueType, params) { - // v3-compat: z.record(valueType, params?) — defaults keyType to z.string() - if (!valueType || !valueType._zod) { - return new ZodRecord({ - type: "record", - keyType: schemas_string(), - valueType: keyType, - ...normalizeParams(valueType), - }); - } - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...util.normalizeParams(params), - partial: true, - }); -} -function looseRecord(keyType, valueType, params) { - return new ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...util.normalizeParams(params), - }); -} -const ZodMap = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodMap", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodMap.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.mapProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_map(keyType, valueType, params) { - return new ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodSet = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSet", (inst, def) => { - _ensureDefaultMemoizer(); - core.$ZodSet.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.setProcessor(inst, ctx, json, params); - inst.min = (...args) => inst.check(core._minSize(...args)); - inst.nonempty = (params) => inst.check(core._minSize(1, params)); - inst.max = (...args) => inst.check(core._maxSize(...args)); - inst.size = (...args) => inst.check(core._size(...args)); -}))); -function schemas_set(valueType, params) { - return new ZodSet({ - type: "set", - valueType: valueType, - ...util.normalizeParams(params), - }); -} -const ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new ZodEnum({ - type: "enum", - entries, - ...util.normalizeParams(params), - }); -} -const ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFile", (inst, def) => { - core.$ZodFile.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.fileProcessor(inst, ctx, json, params); - inst.min = (size, params) => inst.check(core._minSize(size, params)); - inst.max = (size, params) => inst.check(core._maxSize(size, params)); - inst.mime = (types, params) => inst.check(core._mime(Array.isArray(types) ? types : [types], params)); -}))); -function schemas_file(params) { - return core._file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - _ensureDefaultMemoizer(); - $ZodTransform.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - if (!("input" in _issue)) - _issue.input = payload.value; - _issue.inst ?? (_issue.inst = inst); - // _issue.continue ??= true; - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function schemas_optional(innerType) { - return new ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodExactOptional = /*@__PURE__*/ $constructor("ZodExactOptional", (inst, def) => { - $ZodExactOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function exactOptional(innerType) { - return new ZodExactOptional({ - type: "optional", - innerType: innerType, - }); -} -const ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return schemas_optional(nullable(innerType)); -} -const ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodSuccess", (inst, def) => { - core.$ZodSuccess.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.successProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : constantCatch(catchValue)), - }); -} - -const ZodNaN = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodNaN", (inst, def) => { - core.$ZodNaN.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.nanProcessor(inst, ctx, json, params); -}))); -function nan(params) { - return core._nan(ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const ZodCodec = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - core.$ZodCodec.init(inst, def); -}))); -function schemas_codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -function invertCodec(codec) { - const def = codec._zod.def; - return new ZodCodec({ - type: "pipe", - in: def.out, - out: def.in, - transform: def.reverseTransform, - reverseTransform: def.transform, - }); -} -const ZodPreprocess = /*@__PURE__*/ $constructor("ZodPreprocess", (inst, def) => { - ZodPipe.init(inst, def); - $ZodPreprocess.init(inst, def); -}); -const ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodTemplateLiteral", (inst, def) => { - core.$ZodTemplateLiteral.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.templateLiteralProcessor(inst, ctx, json, params); -}))); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...util.normalizeParams(params), - }); -} -const ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const ZodPromise = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodPromise", (inst, def) => { - core.$ZodPromise.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}))); -function schemas_promise(innerType) { - return new ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const ZodFunction = /*@__PURE__*/ (/* unused pure expression or super */ null && (core.$constructor("ZodFunction", (inst, def) => { - core.$ZodFunction.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => processors.functionProcessor(inst, ctx, json, params); -}))); -function _function(params) { - return new ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? schemas_array(unknown())), - output: params?.output ?? unknown(), - }); -} - -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -// custom checks -function schemas_check(fn) { - const ch = new core.$ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function custom(fn, _params) { - return core._custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn, params) { - return _superRefine(fn, params); -} -// Re-export describe and meta from core -const schemas_describe = describe; -const schemas_meta = api_meta; -function _instanceof(cls, params = {}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...util.normalizeParams(params), - }); - inst._zod.bag.Class = cls; - // Override check to emit invalid_type instead of custom - inst._zod.check = (payload) => { - if (!(payload.value instanceof cls)) { - payload.issues.push({ - code: "invalid_type", - expected: cls.name, - input: payload.value, - inst, - path: [...(inst._zod.def.path ?? [])], - }); - } - }; - return inst; -} - -// stringbool -const stringbool = (...args) => core._stringbool({ - Codec: ZodCodec, - Boolean: ZodBoolean, - String: ZodString, -}, ...args); -function schemas_json(params) { - const jsonSchema = lazy(() => { - return schemas_union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), schemas_array(jsonSchema), schemas_record(schemas_string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -function preprocess(fn, schema) { - return new ZodPreprocess({ - type: "pipe", - in: transform(fn), - out: schema, - }); -} - - - - -function iso_datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -function iso_date(params) { - return _isoDate(ZodISODate, params); -} -function iso_time(params) { - return core._isoTime(ZodISOTime, params); -} -function iso_duration(params) { - return core._isoDuration(ZodISODuration, params); -} - -// Zod 3 compat layer - -/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ -const ZodIssueCode = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom", -}; - -/** @deprecated Use `z.config(params)` instead. */ -function setErrorMap(map) { - core.config({ - customError: map, - }); -} -/** @deprecated Use `z.config()` instead. */ -function getErrorMap() { - return core.config().customError; -} -/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ -var compat_ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); - - - -function coerce_string(params) { - return core._coercedString(schemas.ZodString, params); -} -function coerce_number(params) { - return _coercedNumber(ZodNumber, params); -} -function coerce_boolean(params) { - return core._coercedBoolean(schemas.ZodBoolean, params); -} -function coerce_bigint(params) { - return core._coercedBigint(schemas.ZodBigInt, params); -} -function coerce_date(params) { - return core._coercedDate(schemas.ZodDate, params); -} - - - -//#region src/constants.ts -const LATEST_PROTOCOL_VERSION = "2025-11-25"; -const auth_CUe6YdwF_DEFAULT_NEGOTIATED_PROTOCOL_VERSION = "2025-03-26"; -const auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS = [ - LATEST_PROTOCOL_VERSION, - "2025-06-18", - "2025-03-26", - "2024-11-05", - "2024-10-07" -]; -/** -* `_meta` key associating a message with a 2025-11-25 task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task"; -/** -* `_meta` key carrying the MCP protocol version governing a request. -* -* For the HTTP transport, the value must match the `MCP-Protocol-Version` header. -*/ -const auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY = "io.modelcontextprotocol/protocolVersion"; -/** -* `_meta` key identifying the client software making a request. -* -* Clients SHOULD include it on every request; the value is self-reported and -* intended for display, logging, and debugging — servers should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_CLIENT_INFO_META_KEY = "io.modelcontextprotocol/clientInfo"; -/** -* `_meta` key identifying the server software producing a response. -* -* Servers SHOULD include it on every response; the value is self-reported and -* intended for display, logging, and debugging — clients should not rely on -* it for behavior or security decisions. -*/ -const auth_CUe6YdwF_SERVER_INFO_META_KEY = "io.modelcontextprotocol/serverInfo"; -/** -* `_meta` key carrying the client's capabilities for a request. -* -* Capabilities are declared per request rather than once at initialization; -* servers must not infer capabilities from prior requests. -*/ -const auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY = "io.modelcontextprotocol/clientCapabilities"; -/** -* `_meta` key carrying the JSON-RPC ID of the `subscriptions/listen` request -* that opened the stream a notification was delivered on. -* -* Stamped by the server on every notification delivered via a -* `subscriptions/listen` stream (including the leading -* `notifications/subscriptions/acknowledged`); on stdio, where all messages -* share one channel, clients use it to correlate notifications with their -* originating subscription. The value is the listen request's JSON-RPC ID -* verbatim. -*/ -const auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY = "io.modelcontextprotocol/subscriptionId"; -/** -* `_meta` key carrying the desired log level for a request. -* -* When absent, the server must not send `notifications/message` notifications -* for the request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. -*/ -const LOG_LEVEL_META_KEY = "io.modelcontextprotocol/logLevel"; -/** -* `_meta` key carrying W3C Trace Context for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `traceparent` header format, -* e.g. `00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01`. -* -* @see https://www.w3.org/TR/trace-context/#traceparent-header -*/ -const TRACEPARENT_META_KEY = "traceparent"; -/** -* `_meta` key carrying vendor-specific trace state for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C `tracestate` header format, -* e.g. `vendor1=value1,vendor2=value2`. -* -* @see https://www.w3.org/TR/trace-context/#tracestate-header -*/ -const TRACESTATE_META_KEY = "tracestate"; -/** -* `_meta` key carrying cross-cutting propagation values for distributed tracing (SEP-414). -* -* When present, the value MUST follow the W3C Baggage header format, -* e.g. `userId=alice,serverRegion=us-east-1`. -* -* @see https://www.w3.org/TR/baggage/ -*/ -const BAGGAGE_META_KEY = "baggage"; -const JSONRPC_VERSION = "2.0"; -const PARSE_ERROR = (/* unused pure expression or super */ null && (-32700)); -const INVALID_REQUEST = (/* unused pure expression or super */ null && (-32600)); -const METHOD_NOT_FOUND = (/* unused pure expression or super */ null && (-32601)); -const INVALID_PARAMS = (/* unused pure expression or super */ null && (-32602)); -const INTERNAL_ERROR = (/* unused pure expression or super */ null && (-32603)); - -//#endregion -//#region src/schemas.ts -const JSONValueSchema = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema), - schemas_array(JSONValueSchema) -])); -const JSONObjectSchema = schemas_record(schemas_string(), JSONValueSchema); -const JSONArraySchema = schemas_array(JSONValueSchema); -/** -* A progress token, used to associate progress notifications with the original request. -*/ -const ProgressTokenSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* An opaque token used to represent a cursor for pagination. -*/ -const CursorSchema = schemas_string(); -/** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ -const TaskMetadataSchema = schemas_object({ ttl: schemas_number().optional() }); -/** -* Metadata for associating messages with a task. -* Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const RelatedTaskMetadataSchema = schemas_object({ taskId: schemas_string() }); -const RequestMetaSchema = looseObject({ - progressToken: ProgressTokenSchema.optional(), - [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional() -}); -/** -* Common params for any request. -*/ -const BaseRequestParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -/** -* Common params for any task-augmented request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const auth_CUe6YdwF_TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({ task: TaskMetadataSchema.optional() }); -const RequestSchema = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema.loose().optional() -}); -const NotificationsParamsSchema = schemas_object({ _meta: RequestMetaSchema.optional() }); -const NotificationSchema = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema.loose().optional() -}); -/** -* The contents of a result's `_meta` field (the 2026-07-28 `ResultMetaObject`). -* Loose — implementation-specific keys pass through. -* -* The serverInfo key identifies the server software producing the response -* (servers SHOULD include it on every response; the value is self-reported -* and intended for display, logging, and debugging). The getter defers the -* `ImplementationSchema` reference, which is declared later in this file. -*/ -const ResultMetaObjectSchema = looseObject({ get [auth_CUe6YdwF_SERVER_INFO_META_KEY]() { - return ImplementationSchema.optional().catch(void 0); -} }); -const ResultSchema = looseObject({ _meta: ResultMetaObjectSchema.optional() }); -/** -* A uniquely identifying ID for a request in JSON-RPC. -*/ -const RequestIdSchema = schemas_union([schemas_string(), schemas_number().int()]); -/** -* A request that expects a response. -*/ -const JSONRPCRequestSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - ...RequestSchema.shape -}).strict(); -/** -* A notification which does not expect a response. -*/ -const JSONRPCNotificationSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - ...NotificationSchema.shape -}).strict(); -/** -* A successful (non-error) response to a request. -*/ -const JSONRPCResultResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema, - result: ResultSchema -}).strict(); -/** -* A response to a request that indicates an error occurred. -*/ -const JSONRPCErrorResponseSchema = schemas_object({ - jsonrpc: literal(JSONRPC_VERSION), - id: RequestIdSchema.optional(), - error: schemas_object({ - code: schemas_number().int(), - message: schemas_string(), - data: unknown().optional() - }) -}).strict(); -const auth_CUe6YdwF_JSONRPCMessageSchema = schemas_union([ - JSONRPCRequestSchema, - JSONRPCNotificationSchema, - JSONRPCResultResponseSchema, - JSONRPCErrorResponseSchema -]); -const auth_CUe6YdwF_JSONRPCResponseSchema = schemas_union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]); -/** -* A response that indicates success but carries no data. -*/ -const EmptyResultSchema = ResultSchema.strict(); -const CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({ - requestId: RequestIdSchema.optional(), - reason: schemas_string().optional() -}); -/** -* This notification can be sent by either side to indicate that it is cancelling a previously-issued request. -* -* The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. -* -* This notification indicates that the result will be unused, so any associated processing SHOULD cease. -* -* A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. -*/ -const CancelledNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema -}); -/** -* Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. -*/ -const IconSchema = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() -}); -/** -* Base schema to add `icons` property. -* -*/ -const IconsSchema = schemas_object({ icons: schemas_array(IconSchema).optional() }); -/** -* Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. -*/ -const BaseMetadataSchema = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() -}); -/** -* Describes the name and version of an MCP implementation. -*/ -const ImplementationSchema = BaseMetadataSchema.extend({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() -}); -const auth_CUe6YdwF_FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema); -const auth_CUe6YdwF_ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; -}, intersection(schemas_object({ - form: auth_CUe6YdwF_FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema.optional() -}), JSONObjectSchema.optional())); -/** -* Task capabilities for clients, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ClientTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema.optional() }).optional() - }).optional() -}); -/** -* Task capabilities for servers, indicating which request types support task creation. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ServerTasksCapabilitySchema = looseObject({ - list: JSONObjectSchema.optional(), - cancel: JSONObjectSchema.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema.optional() }).optional() }).optional() -}); -/** -* Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. -*/ -const ClientCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - sampling: schemas_object({ - context: JSONObjectSchema.optional(), - tools: JSONObjectSchema.optional() - }).optional(), - elicitation: auth_CUe6YdwF_ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -const InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema, - clientInfo: ImplementationSchema -}); -/** -* This request is sent from the client to the server when it first connects, asking it to begin initialization. -*/ -const auth_CUe6YdwF_InitializeRequestSchema = RequestSchema.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema -}); -/** -* Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. -*/ -const ServerCapabilitiesSchema = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema).optional(), - logging: JSONObjectSchema.optional(), - completions: JSONObjectSchema.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema).optional() -}); -/** -* After receiving an initialize request from the client, the server sends this response. -*/ -const InitializeResultSchema = ResultSchema.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema, - serverInfo: ImplementationSchema, - instructions: schemas_string().optional() -}); -/** -* This notification is sent from the client to the server after initialization has finished. -*/ -const auth_CUe6YdwF_InitializedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema.optional() -}); -/** -* A request from the client asking the server to advertise its supported protocol -* versions, capabilities, and other metadata (protocol revision 2026-07-28). Servers -* MUST implement `server/discover`. Clients MAY call it but are not required to — -* version negotiation can also happen inline via the per-request `_meta` envelope. -*/ -const DiscoverRequestSchema = RequestSchema.extend({ - method: literal("server/discover"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The result returned by the server for a `server/discover` request. -*/ -const DiscoverResultSchema = ResultSchema.extend({ - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilitiesSchema, - instructions: schemas_string().optional() -}); -/** -* A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. -*/ -const PingRequestSchema = RequestSchema.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema.optional() -}); -const ProgressSchema = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) -}); -const ProgressNotificationParamsSchema = schemas_object({ - ...NotificationsParamsSchema.shape, - ...ProgressSchema.shape, - progressToken: ProgressTokenSchema -}); -/** -* An out-of-band notification used to inform the receiver of a progress update for a long-running request. -* -* @category notifications/progress -*/ -const ProgressNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema -}); -const PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({ cursor: CursorSchema.optional() }); -const PaginatedRequestSchema = RequestSchema.extend({ params: PaginatedRequestParamsSchema.optional() }); -const PaginatedResultSchema = ResultSchema.extend({ nextCursor: CursorSchema.optional() }); -/** -* The contents of a specific resource or sub-resource. -*/ -const ResourceContentsSchema = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -const TextResourceContentsSchema = ResourceContentsSchema.extend({ text: schemas_string() }); -/** -* A Zod schema for validating Base64 strings that is more performant and -* robust for very large inputs than the default regex-based check. It avoids -* stack overflows by using the native `atob` function for validation. -*/ -const auth_CUe6YdwF_Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } -}, { message: "Invalid Base64 string" }); -const BlobResourceContentsSchema = ResourceContentsSchema.extend({ blob: auth_CUe6YdwF_Base64Schema }); -/** -* The sender or recipient of messages and data in a conversation. -*/ -const RoleSchema = schemas_enum(["user", "assistant"]); -/** -* Optional annotations providing clients additional context about a resource. -*/ -const AnnotationsSchema = schemas_object({ - audience: schemas_array(RoleSchema).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() -}); -/** -* A known resource that the server is capable of reading. -*/ -const ResourceSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* A template description for resources available on the server. -*/ -const ResourceTemplateSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema.optional(), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of resources the server has. -*/ -const ListResourcesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/list") }); -/** -* The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. -*/ -const ListResourcesResultSchema = PaginatedResultSchema.extend({ resources: schemas_array(ResourceSchema) }); -/** -* Sent from the client to request a list of resource templates the server has. -*/ -const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({ method: literal("resources/templates/list") }); -/** -* The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. -*/ -const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema) }); -const ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({ uri: schemas_string() }); -/** -* Parameters for a {@linkcode ReadResourceRequest | resources/read} request. -*/ -const ReadResourceRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to the server, to read a specific resource URI. -*/ -const ReadResourceRequestSchema = RequestSchema.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema -}); -/** -* The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. -*/ -const ReadResourceResultSchema = ResultSchema.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema])) }); -/** -* An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ResourceListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema.optional() -}); -const SubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. -*/ -const SubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema -}); -const UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema; -/** -* Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const UnsubscribeRequestSchema = RequestSchema.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema -}); -/** -* The set of notification types a client opts in to on a `subscriptions/listen` -* request. Each type is opt-in; the server MUST NOT send a notification type -* the client has not explicitly requested here. -*/ -const SubscriptionFilterSchema = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() -}); -const SubscriptionsListenRequestParamsSchema = BaseRequestParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent from the client to open a long-lived channel for receiving notifications -* outside the context of a specific request (protocol revision 2026-07-28). -* Replaces the previous HTTP GET endpoint and `resources/subscribe`. -*/ -const SubscriptionsListenRequestSchema = RequestSchema.extend({ - method: literal("subscriptions/listen"), - params: SubscriptionsListenRequestParamsSchema -}); -const SubscriptionsAcknowledgedNotificationParamsSchema = NotificationsParamsSchema.extend({ notifications: SubscriptionFilterSchema }); -/** -* Sent by the server as the first message on a `subscriptions/listen` stream -* to acknowledge that the subscription has been established and report which -* notification types it agreed to honor (protocol revision 2026-07-28). -*/ -const SubscriptionsAcknowledgedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/subscriptions/acknowledged"), - params: SubscriptionsAcknowledgedNotificationParamsSchema -}); -/** -* `_meta` for a {@linkcode SubscriptionsListenResult}: the listen request's -* JSON-RPC ID under the canonical subscription-id key (mirroring the same key -* on every notification delivered on the stream). Extends -* {@linkcode ResultMetaObjectSchema}, so the optional serverInfo key is typed -* here too. -*/ -const SubscriptionsListenResultMetaSchema = ResultMetaObjectSchema.extend({ [auth_CUe6YdwF_SUBSCRIPTION_ID_META_KEY]: RequestIdSchema }); -/** -* The response to a `subscriptions/listen` request, signalling that the -* subscription has ended gracefully (for example, during server shutdown). -* Because the listen stream is long-lived, this result is sent only when the -* server tears the subscription down; an abrupt transport close carries no -* response. The result body is otherwise empty. -*/ -const SubscriptionsListenResultSchema = ResultSchema.extend({ _meta: SubscriptionsListenResultMetaSchema }); -/** -* Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. -*/ -const ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({ uri: schemas_string() }); -/** -* A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. -*/ -const ResourceUpdatedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema -}); -/** -* Describes an argument that a prompt can accept. -*/ -const PromptArgumentSchema = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) -}); -/** -* A prompt or prompt template that the server offers. -*/ -const PromptSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema)), - _meta: schemas_optional(looseObject({})) -}); -/** -* Sent from the client to request a list of prompts and prompt templates the server has. -*/ -const ListPromptsRequestSchema = PaginatedRequestSchema.extend({ method: literal("prompts/list") }); -/** -* The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. -*/ -const ListPromptsResultSchema = PaginatedResultSchema.extend({ prompts: schemas_array(PromptSchema) }); -/** -* Parameters for a {@linkcode GetPromptRequest | prompts/get} request. -*/ -const GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() -}); -/** -* Used by the client to get a prompt provided by the server. -*/ -const GetPromptRequestSchema = RequestSchema.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema -}); -/** -* Text provided to or from an LLM. -*/ -const TextContentSchema = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* An image provided to or from an LLM. -*/ -const ImageContentSchema = schemas_object({ - type: literal("image"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Audio content provided to or from an LLM. -*/ -const AudioContentSchema = schemas_object({ - type: literal("audio"), - data: auth_CUe6YdwF_Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A tool call request from an assistant (LLM). -* Represents the assistant's request to use a tool. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolUseContentSchema = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* The contents of a resource, embedded into a prompt or tool call result. -*/ -const EmbeddedResourceSchema = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema, BlobResourceContentsSchema]), - annotations: AnnotationsSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* A resource that the server is capable of reading, included in a prompt or tool call result. -* -* Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. -*/ -const ResourceLinkSchema = ResourceSchema.extend({ type: literal("resource_link") }); -/** -* A content block that can be used in prompts and tool results. -*/ -const ContentBlockSchema = schemas_union([ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ResourceLinkSchema, - EmbeddedResourceSchema -]); -/** -* Describes a message returned as part of a prompt. -*/ -const PromptMessageSchema = schemas_object({ - role: RoleSchema, - content: ContentBlockSchema -}); -/** -* The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. -*/ -const GetPromptResultSchema = ResultSchema.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema) -}); -/** -* An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const PromptListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Additional properties describing a `Tool` to clients. -* -* NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. -* They are not guaranteed to provide a faithful description of -* tool behavior (including descriptive properties like `title`). -* -* Clients should never make tool use decisions based on `ToolAnnotations` -* received from untrusted servers. -*/ -const ToolAnnotationsSchema = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() -}); -/** -* Execution-related properties for a tool. -*/ -const ToolExecutionSchema = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" -]).optional() }); -/** -* Definition for a tool the client can call. -*/ -const ToolSchema = schemas_object({ - ...BaseMetadataSchema.shape, - ...IconsSchema.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema.optional(), - execution: ToolExecutionSchema.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the client to request a list of tools the server has. -*/ -const ListToolsRequestSchema = PaginatedRequestSchema.extend({ method: literal("tools/list") }); -/** -* The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. -*/ -const ListToolsResultSchema = PaginatedResultSchema.extend({ tools: schemas_array(ToolSchema) }); -/** -* The server's response to a tool call. -*/ -const auth_CUe6YdwF_CallToolResultSchema = ResultSchema.extend({ - content: schemas_array(ContentBlockSchema).default([]), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() -}); -/** -* {@linkcode CallToolResultSchema} extended with backwards compatibility to protocol version 2024-10-07. -*/ -const CompatibilityCallToolResultSchema = auth_CUe6YdwF_CallToolResultSchema.or(ResultSchema.extend({ toolResult: unknown() })); -/** -* Parameters for a `tools/call` request. -*/ -const CallToolRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Used by the client to invoke a tool provided by the server. -*/ -const CallToolRequestSchema = RequestSchema.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema -}); -/** -* An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. -*/ -const ToolListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Base schema for list changed subscription options (without callback). -* Used internally for Zod validation of `autoRefresh` and `debounceMs`. -*/ -const ListChangedOptionsBaseSchema = schemas_object({ - autoRefresh: schemas_boolean().default(true), - debounceMs: schemas_number().int().nonnegative().default(300) -}); -/** -* The severity of a log message. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingLevelSchema = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" -]); -/** -* Parameters for a `logging/setLevel` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({ level: LoggingLevelSchema }); -/** -* A request from the client to the server, to enable or adjust logging. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const SetLevelRequestSchema = RequestSchema.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema -}); -/** -* Parameters for a `notifications/message` notification. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({ - level: LoggingLevelSchema, - logger: schemas_string().optional(), - data: unknown() -}); -/** -* Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to stderr logging -* (STDIO servers) or OpenTelemetry. -*/ -const LoggingMessageNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema -}); -/** -* Hints to use for model selection. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelHintSchema = schemas_object({ name: schemas_string().optional() }); -/** -* The server's preferences for model selection, requested of the client during sampling. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ModelPreferencesSchema = schemas_object({ - hints: schemas_array(ModelHintSchema).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() -}); -/** -* Controls tool usage behavior in sampling requests. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolChoiceSchema = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" -]).optional() }); -/** -* The result of a tool execution, provided by the user (server). -* Represents the outcome of invoking a tool requested via `ToolUseContent`. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const ToolResultContentSchema = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Basic content types for sampling responses (without tool use). -* Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingContentSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema -]); -/** -* Content block types allowed in sampling messages. -* This includes text, image, audio, tool use requests, and tool results. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageContentBlockSchema = discriminatedUnion("type", [ - TextContentSchema, - ImageContentSchema, - AudioContentSchema, - ToolUseContentSchema, - ToolResultContentSchema -]); -/** -* Describes a message issued to or received from an LLM API. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const SamplingMessageSchema = schemas_object({ - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Parameters for a `sampling/createMessage` request. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - messages: schemas_array(SamplingMessageSchema), - modelPreferences: ModelPreferencesSchema.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema.optional(), - tools: schemas_array(ToolSchema).optional(), - toolChoice: ToolChoiceSchema.optional() -}); -/** -* A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageRequestSchema = RequestSchema.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema -}); -/** -* The client's response to a `sampling/create_message` request from the server. -* This is the backwards-compatible version that returns single content (no arrays). -* Used when the request does not include tools. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema, - content: SamplingContentSchema -}); -/** -* The client's response to a `sampling/create_message` request when tools were provided. -* This version supports array content for tool use flows. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to calling LLM -* provider APIs directly. -*/ -const CreateMessageResultWithToolsSchema = ResultSchema.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema, - content: schemas_union([SamplingMessageContentBlockSchema, schemas_array(SamplingMessageContentBlockSchema)]) -}); -/** -* Primitive schema definition for boolean fields. -*/ -const BooleanSchemaSchema = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() -}); -/** -* Primitive schema definition for string fields. -*/ -const StringSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() -}); -/** -* Primitive schema definition for number fields. -*/ -const NumberSchemaSchema = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() -}); -/** -* Schema for single-selection enumeration without display titles for options. -*/ -const UntitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() -}); -/** -* Schema for single-selection enumeration with display titles for each option. -*/ -const TitledSingleSelectEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() -}); -/** -* Use {@linkcode TitledSingleSelectEnumSchema} instead. -* This interface will be removed in a future version. -*/ -const LegacyTitledEnumSchemaSchema = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() -}); -const SingleSelectEnumSchemaSchema = schemas_union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]); -/** -* Schema for multiple-selection enumeration without display titles for options. -*/ -const UntitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Schema for multiple-selection enumeration with display titles for each option. -*/ -const TitledMultiSelectEnumSchemaSchema = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() -}); -/** -* Combined schema for multiple-selection enumeration -*/ -const MultiSelectEnumSchemaSchema = schemas_union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]); -/** -* Primitive schema definition for enum fields. -*/ -const EnumSchemaSchema = schemas_union([ - LegacyTitledEnumSchemaSchema, - SingleSelectEnumSchemaSchema, - MultiSelectEnumSchemaSchema -]); -/** -* Union of all primitive schema definitions. -*/ -const PrimitiveSchemaDefinitionSchema = schemas_union([ - EnumSchemaSchema, - BooleanSchemaSchema, - StringSchemaSchema, - NumberSchemaSchema -]); -/** -* Parameters for an `elicitation/create` request for form-based elicitation. -*/ -const ElicitRequestFormParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) -}); -/** -* Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. -*/ -const ElicitRequestURLParamsSchema = auth_CUe6YdwF_TaskAugmentedRequestParamsSchema.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() -}); -/** -* The parameters for a request to elicit additional information from the user via the client. -*/ -const ElicitRequestParamsSchema = schemas_union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]); -/** -* A request from the server to elicit user input via the client. -* The client should present the message and form fields to the user (form mode) -* or navigate to a URL (URL mode). -*/ -const ElicitRequestSchema = RequestSchema.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema -}); -/** -* Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({ elicitationId: schemas_string() }); -/** -* A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. -* -* @deprecated Removed from the spec by #2891 (2026-07-28). The client learns the outcome -* of an out-of-band interaction by retrying the original request; no server-initiated -* completion signal exists in the 2026-07-28 revision. Kept here for the 2025-era flow -* only. The 2026-07-28 wire codec excludes this notification. -* @category notifications/elicitation/complete -*/ -const ElicitationCompleteNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema -}); -/** -* The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. -*/ -const ElicitResultSchema = ResultSchema.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) -}); -/** -* A reference to a resource or resource template definition. -*/ -const ResourceTemplateReferenceSchema = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() -}); -/** -* Identifies a prompt. -*/ -const PromptReferenceSchema = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() -}); -/** -* Parameters for a {@linkcode CompleteRequest | completion/complete} request. -*/ -const CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({ - ref: schemas_union([PromptReferenceSchema, ResourceTemplateReferenceSchema]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() -}); -/** -* A request from the client to the server, to ask for completion options. -*/ -const CompleteRequestSchema = RequestSchema.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema -}); -/** -* The server's response to a {@linkcode CompleteRequest | completion/complete} request -*/ -const CompleteResultSchema = ResultSchema.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) -}) }); -/** -* Represents a root directory or file that the server can operate on. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootSchema = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() -}); -/** -* Sent from the server to request a list of root URIs from the client. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsRequestSchema = RequestSchema.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema.optional() -}); -/** -* The client's response to a `roots/list` request from the server. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const ListRootsResultSchema = ResultSchema.extend({ roots: schemas_array(RootSchema) }); -/** -* A notification from the client to the server, informing it that the list of roots has changed. -* -* @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains -* in the specification for at least twelve months. Migrate to passing paths via -* tool parameters, resource URIs, or configuration. -*/ -const RootsListChangedNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema.optional() -}); -/** -* Task creation parameters, used to ask that the server create a task to represent a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskCreationParamsSchema = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() -}); -/** -* The status of a task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusSchema = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" -]); -/** -* A pollable state object associated with a request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskSchema = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) -}); -/** -* Result returned when a task is created, containing the task data wrapped in a `task` field. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CreateTaskResultSchema = ResultSchema.extend({ task: TaskSchema }); -/** -* Parameters for task status notification. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema); -/** -* A notification sent when a task's status changes. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const TaskStatusNotificationSchema = NotificationSchema.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema -}); -/** -* A request to get the state of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode GetTaskRequest | tasks/get} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskResultSchema = ResultSchema.merge(TaskSchema); -/** -* A request to get the result of a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadRequestSchema = RequestSchema.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a `tasks/result` request. -* The structure matches the result type of the original request. -* For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. -* -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const GetTaskPayloadResultSchema = ResultSchema.loose(); -/** -* A request to list tasks. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksRequestSchema = PaginatedRequestSchema.extend({ method: literal("tasks/list") }); -/** -* The response to a {@linkcode ListTasksRequest | tasks/list} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const ListTasksResultSchema = PaginatedResultSchema.extend({ tasks: schemas_array(TaskSchema) }); -/** -* A request to cancel a specific task. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskRequestSchema = RequestSchema.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema.extend({ taskId: schemas_string() }) -}); -/** -* The response to a {@linkcode CancelTaskRequest | tasks/cancel} request. -* -* @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. -*/ -const CancelTaskResultSchema = ResultSchema.merge(TaskSchema); -const ClientRequestSchema = schemas_union([ - PingRequestSchema, - auth_CUe6YdwF_InitializeRequestSchema, - DiscoverRequestSchema, - CompleteRequestSchema, - SetLevelRequestSchema, - GetPromptRequestSchema, - ListPromptsRequestSchema, - ListResourcesRequestSchema, - ListResourceTemplatesRequestSchema, - ReadResourceRequestSchema, - SubscribeRequestSchema, - UnsubscribeRequestSchema, - SubscriptionsListenRequestSchema, - CallToolRequestSchema, - ListToolsRequestSchema -]); -const ClientNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - auth_CUe6YdwF_InitializedNotificationSchema, - RootsListChangedNotificationSchema -]); -const ClientResultSchema = schemas_union([ - EmptyResultSchema, - CreateMessageResultSchema, - CreateMessageResultWithToolsSchema, - ElicitResultSchema, - ListRootsResultSchema -]); -const ServerRequestSchema = schemas_union([ - PingRequestSchema, - CreateMessageRequestSchema, - ElicitRequestSchema, - ListRootsRequestSchema -]); -const ServerNotificationSchema = schemas_union([ - CancelledNotificationSchema, - ProgressNotificationSchema, - LoggingMessageNotificationSchema, - ResourceUpdatedNotificationSchema, - ResourceListChangedNotificationSchema, - ToolListChangedNotificationSchema, - PromptListChangedNotificationSchema, - SubscriptionsAcknowledgedNotificationSchema, - ElicitationCompleteNotificationSchema -]); -const ServerResultSchema = schemas_union([ - EmptyResultSchema, - InitializeResultSchema, - DiscoverResultSchema, - CompleteResultSchema, - GetPromptResultSchema, - ListPromptsResultSchema, - ListResourcesResultSchema, - ListResourceTemplatesResultSchema, - ReadResourceResultSchema, - auth_CUe6YdwF_CallToolResultSchema, - ListToolsResultSchema, - SubscriptionsListenResultSchema -]); - -//#endregion -//#region src/auth.ts -/** -* Reusable URL validation that disallows `javascript:` scheme -*/ -const SafeUrlSchema = schemas_url().superRefine((val, ctx) => { - if (!URL.canParse(val)) { - ctx.addIssue({ - code: ZodIssueCode.custom, - message: "URL must be parseable", - fatal: true - }); - return NEVER; - } -}).refine((url) => { - const u = new URL(url); - return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:"; -}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" }); -/** -* RFC 9728 OAuth Protected Resource Metadata -*/ -const OAuthProtectedResourceMetadataSchema = looseObject({ - resource: schemas_string().url(), - authorization_servers: schemas_array(SafeUrlSchema).optional(), - jwks_uri: schemas_string().url().optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - bearer_methods_supported: schemas_array(schemas_string()).optional(), - resource_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - resource_name: schemas_string().optional(), - resource_documentation: schemas_string().optional(), - resource_policy_uri: schemas_string().url().optional(), - resource_tos_uri: schemas_string().url().optional(), - tls_client_certificate_bound_access_tokens: schemas_boolean().optional(), - authorization_details_types_supported: schemas_array(schemas_string()).optional(), - dpop_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - dpop_bound_access_tokens_required: schemas_boolean().optional() -}); -/** -* RFC 8414 OAuth 2.0 Authorization Server Metadata -*/ -const OAuthMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - service_documentation: SafeUrlSchema.optional(), - revocation_endpoint: SafeUrlSchema.optional(), - revocation_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - revocation_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint: schemas_string().optional(), - introspection_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - introspection_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - code_challenge_methods_supported: schemas_array(schemas_string()).optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery 1.0 Provider Metadata -* -* @see https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata -*/ -const OpenIdProviderMetadataSchema = looseObject({ - issuer: schemas_string(), - authorization_endpoint: SafeUrlSchema, - token_endpoint: SafeUrlSchema, - userinfo_endpoint: SafeUrlSchema.optional(), - jwks_uri: SafeUrlSchema, - registration_endpoint: SafeUrlSchema.optional(), - scopes_supported: schemas_array(schemas_string()).optional(), - response_types_supported: schemas_array(schemas_string()), - response_modes_supported: schemas_array(schemas_string()).optional(), - grant_types_supported: schemas_array(schemas_string()).optional(), - acr_values_supported: schemas_array(schemas_string()).optional(), - subject_types_supported: schemas_array(schemas_string()), - id_token_signing_alg_values_supported: schemas_array(schemas_string()), - id_token_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - id_token_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - userinfo_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - userinfo_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - request_object_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_alg_values_supported: schemas_array(schemas_string()).optional(), - request_object_encryption_enc_values_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_methods_supported: schemas_array(schemas_string()).optional(), - token_endpoint_auth_signing_alg_values_supported: schemas_array(schemas_string()).optional(), - display_values_supported: schemas_array(schemas_string()).optional(), - claim_types_supported: schemas_array(schemas_string()).optional(), - claims_supported: schemas_array(schemas_string()).optional(), - service_documentation: schemas_string().optional(), - claims_locales_supported: schemas_array(schemas_string()).optional(), - ui_locales_supported: schemas_array(schemas_string()).optional(), - claims_parameter_supported: schemas_boolean().optional(), - request_parameter_supported: schemas_boolean().optional(), - request_uri_parameter_supported: schemas_boolean().optional(), - require_request_uri_registration: schemas_boolean().optional(), - op_policy_uri: SafeUrlSchema.optional(), - op_tos_uri: SafeUrlSchema.optional(), - client_id_metadata_document_supported: schemas_boolean().optional(), - authorization_response_iss_parameter_supported: schemas_boolean().optional().catch(void 0) -}); -/** -* OpenID Connect Discovery metadata that may include OAuth 2.0 fields -* This schema represents the real-world scenario where OIDC providers -* return a mix of OpenID Connect and OAuth 2.0 metadata fields -*/ -const OpenIdProviderDiscoveryMetadataSchema = schemas_object({ - ...OpenIdProviderMetadataSchema.shape, - ...OAuthMetadataSchema.pick({ code_challenge_methods_supported: true }).shape -}); -/** -* OAuth 2.1 token response -*/ -const OAuthTokensSchema = schemas_object({ - access_token: schemas_string(), - id_token: schemas_string().optional(), - token_type: schemas_string(), - expires_in: coerce_number().optional(), - scope: schemas_string().optional(), - refresh_token: schemas_string().optional() -}).strip(); -/** -* RFC 8693 §2.2.1 Token Exchange response for ID-JAG tokens. -* -* `token_type` is intentionally optional: per RFC 8693 §2.2.1 it is informational when -* the issued token is not an access token, and per RFC 6749 §5.1 it is case-insensitive, -* so strict checking rejects conformant IdPs. -*/ -const IdJagTokenExchangeResponseSchema = schemas_object({ - issued_token_type: literal("urn:ietf:params:oauth:token-type:id-jag"), - access_token: schemas_string(), - token_type: schemas_string().optional(), - expires_in: schemas_number().optional(), - scope: schemas_string().optional() -}).strip(); -/** -* OAuth 2.1 error response -*/ -const OAuthErrorResponseSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional(), - error_uri: schemas_string().optional() -}); -/** -* Optional version of {@linkcode SafeUrlSchema} that allows empty string for backward compatibility on `tos_uri` and `logo_uri` -*/ -const OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0)); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration metadata -*/ -const OAuthClientMetadataSchema = schemas_object({ - redirect_uris: schemas_array(SafeUrlSchema), - token_endpoint_auth_method: schemas_string().optional(), - grant_types: schemas_array(schemas_string()).optional(), - response_types: schemas_array(schemas_string()).optional(), - application_type: schemas_string().optional(), - client_name: schemas_string().optional(), - client_uri: SafeUrlSchema.optional(), - logo_uri: OptionalSafeUrlSchema, - scope: schemas_string().optional(), - contacts: schemas_array(schemas_string()).optional(), - tos_uri: OptionalSafeUrlSchema, - policy_uri: schemas_string().optional(), - jwks_uri: SafeUrlSchema.optional(), - jwks: any().optional(), - software_id: schemas_string().optional(), - software_version: schemas_string().optional(), - software_statement: schemas_string().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration client information -*/ -const OAuthClientInformationSchema = schemas_object({ - client_id: schemas_string(), - client_secret: schemas_string().optional(), - client_id_issued_at: schemas_number().optional(), - client_secret_expires_at: schemas_number().optional() -}).strip(); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration full response (client information plus metadata) -*/ -const OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema); -/** -* RFC 7591 OAuth 2.0 Dynamic Client Registration error response -*/ -const OAuthClientRegistrationErrorSchema = schemas_object({ - error: schemas_string(), - error_description: schemas_string().optional() -}).strip(); -/** -* RFC 7009 OAuth 2.0 Token Revocation request -*/ -const OAuthTokenRevocationRequestSchema = schemas_object({ - token: schemas_string(), - token_type_hint: schemas_string().optional() -}).strip(); - -//#endregion - -//# sourceMappingURL=auth-CUe6YdwF.mjs.map - - - - - - - - -//#region ../core-internal/src/errors/crossBundleBrand.ts -/** -* Cross-bundle `instanceof` support for the SDK error classes. -* -* `@modelcontextprotocol/client` and `@modelcontextprotocol/server` each bundle their -* own copy of `core-internal`, so an error constructed by one package fails a -* prototype-identity `instanceof` against the same class re-exported by the other — -* exactly the check a dual-role process (gateway, host, in-process test) writes. -* -* Instead of prototype identity, branded classes stamp every instance with the brand -* strings of its class chain under a registry symbol (`Symbol.for`, shared across -* bundles and realms), and resolve `instanceof` via `Symbol.hasInstance` against the -* brand set. Ordinary prototype-based `instanceof` is kept as a fallback so behavior -* is unchanged for anything unbranded. -* -* A class participates by defining an **own** `mcpBrand` static (via a `static {}` -* block, so nothing reaches the declaration files — a declared `protected static` -* field would make the constructor types nominally incompatible across the bundled -* copies) and (for hierarchy roots) installing {@linkcode brandedHasInstance} as -* `Symbol.hasInstance`. User-defined subclasses that do not declare their own brand -* keep plain prototype semantics — a foreign base-class instance never satisfies -* `instanceof UserSubclass`. -* -* Prior art — the same stamp-and-hook shape ships at scale elsewhere: Node core -* (stream.Writable since 2017, Console via a marker symbol, diagnostics_channel), -* undici's whole error hierarchy (vendored into Node as fetch), googleapis/gaxios -* (GaxiosError, Symbol.for marker), AWS SDK v3's ServiceException (which pairs a -* Symbol.hasInstance override with a static isInstance guard, as we do), and zod v4 -* (Symbol.hasInstance on every schema class for cross-version interop). -* -* Contract notes: -* - Participation criterion: **every error class exported from a public package that -* callers are documented to `instanceof` must be branded.** The per-package -* errorBrandConformance tests walk the export surfaces and fail naming any -* exported Error subclass that has not opted in. -* - Brands assert **identity, not shape**: brand strings are version-less, so an -* instance from one SDK version matches the class of another. Members added to a -* branded class in a later version may be absent on a matched instance — read -* fields defensively, and treat branded classes as additive-only. The escape -* hatch when a release must break a branded class's read contract: change that -* class's brand string in the same release, which cleanly severs cross-version -* matching for that class. The per-package brand pins make the rename -* deliberate: errorSurfacePins.test.ts owns the core-internal brands, and each -* package's errorBrandConformance test pins its package-local ones. -* - Cross-bundle matching requires **both** copies to be at or after the release -* that introduced branding; against an older copy, behavior degrades to plain -* prototype `instanceof` in both directions. -* - A consumer re-bundling the SDK with property mangling (`mangle.props`) would -* break the brand statics; default esbuild/webpack/terser settings do not. -*/ -/** Registry symbol — identical across bundled copies and realms. */ -const BRANDS = Symbol.for("mcp.sdk.errorBrands"); -/** -* Stamp `instance` with the brand of every class in `ctor`'s chain that declares an -* own `mcpBrand`. Call once from the hierarchy root's constructor with `new.target` — -* subclasses inherit the stamping without touching their constructors. -* -* Constructor-time only: never stamp arbitrary objects. A stamped non-instance would -* satisfy `instanceof` while lacking the prototype members (getters like `.status`) -* that callers reach for after the check. -*/ -function stampErrorBrands(instance, ctor) { - const brands = /* @__PURE__ */ new Set(); - let current = ctor; - while (typeof current === "function") { - const brand = current.mcpBrand; - if (Object.prototype.hasOwnProperty.call(current, "mcpBrand") && typeof brand === "string") brands.add(brand); - current = Object.getPrototypeOf(current); - } - if (brands.size === 0) return; - Object.defineProperty(instance, BRANDS, { - value: brands, - enumerable: false, - configurable: true - }); -} -/** -* `Symbol.hasInstance` implementation for branded hierarchy roots. Matches when the -* value carries the **own** brand of the class being tested against (cross-bundle -* path), falling back to ordinary prototype-based `instanceof` otherwise. -*/ -function brandedHasInstance(cls, value) { - try { - if (typeof value === "object" && value !== null && Object.prototype.hasOwnProperty.call(cls, "mcpBrand") && typeof cls.mcpBrand === "string" && Object.prototype.hasOwnProperty.call(value, BRANDS)) { - const carried = value[BRANDS]; - if (carried && typeof carried.has === "function" && carried.has(cls.mcpBrand)) return true; - } - } catch {} - return Function.prototype[Symbol.hasInstance].call(cls, value); -} - -//#endregion -//#region ../core-internal/src/auth/errors.ts -/** -* OAuth error codes as defined by {@link https://datatracker.ietf.org/doc/html/rfc6749#section-5.2 | RFC 6749} -* and extensions. -*/ -let src_CX2iR2pK_OAuthErrorCode = /* @__PURE__ */ (/* unused pure expression or super */ null && (function(OAuthErrorCode$1) { - /** - * The request is missing a required parameter, includes an invalid parameter value, - * includes a parameter more than once, or is otherwise malformed. - */ - OAuthErrorCode$1["InvalidRequest"] = "invalid_request"; - /** - * Client authentication failed (e.g., unknown client, no client authentication included, - * or unsupported authentication method). - */ - OAuthErrorCode$1["InvalidClient"] = "invalid_client"; - /** - * The provided authorization grant or refresh token is invalid, expired, revoked, - * does not match the redirection URI used in the authorization request, or was issued to another client. - */ - OAuthErrorCode$1["InvalidGrant"] = "invalid_grant"; - /** - * The authenticated client is not authorized to use this authorization grant type. - */ - OAuthErrorCode$1["UnauthorizedClient"] = "unauthorized_client"; - /** - * The authorization grant type is not supported by the authorization server. - */ - OAuthErrorCode$1["UnsupportedGrantType"] = "unsupported_grant_type"; - /** - * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. - */ - OAuthErrorCode$1["InvalidScope"] = "invalid_scope"; - /** - * The resource owner or authorization server denied the request. - */ - OAuthErrorCode$1["AccessDenied"] = "access_denied"; - /** - * The authorization server encountered an unexpected condition that prevented it from fulfilling the request. - */ - OAuthErrorCode$1["ServerError"] = "server_error"; - /** - * The authorization server is currently unable to handle the request due to temporary overloading or maintenance. - */ - OAuthErrorCode$1["TemporarilyUnavailable"] = "temporarily_unavailable"; - /** - * The authorization server does not support obtaining an authorization code using this method. - */ - OAuthErrorCode$1["UnsupportedResponseType"] = "unsupported_response_type"; - /** - * The authorization server does not support the requested token type. - */ - OAuthErrorCode$1["UnsupportedTokenType"] = "unsupported_token_type"; - /** - * The access token provided is expired, revoked, malformed, or invalid for other reasons. - */ - OAuthErrorCode$1["InvalidToken"] = "invalid_token"; - /** - * The HTTP method used is not allowed for this endpoint. (Custom, non-standard error) - */ - OAuthErrorCode$1["MethodNotAllowed"] = "method_not_allowed"; - /** - * Rate limit exceeded. (Custom, non-standard error based on RFC 6585) - */ - OAuthErrorCode$1["TooManyRequests"] = "too_many_requests"; - /** - * The client metadata is invalid. (Custom error for dynamic client registration - RFC 7591) - */ - OAuthErrorCode$1["InvalidClientMetadata"] = "invalid_client_metadata"; - /** - * The value of one or more redirection URIs is invalid. (Dynamic client registration - RFC 7591 §3.2.2) - */ - OAuthErrorCode$1["InvalidRedirectUri"] = "invalid_redirect_uri"; - /** - * The request requires higher privileges than provided by the access token. - */ - OAuthErrorCode$1["InsufficientScope"] = "insufficient_scope"; - /** - * The requested resource is invalid, missing, unknown, or malformed. (Custom error for resource indicators - RFC 8707) - */ - OAuthErrorCode$1["InvalidTarget"] = "invalid_target"; - return OAuthErrorCode$1; -}({}))); -/** -* OAuth error class for all OAuth-related errors. -*/ -var src_CX2iR2pK_OAuthError = class OAuthError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.OAuthError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, errorUri) { - super(message); - this.code = code; - this.errorUri = errorUri; - this.name = "OAuthError"; - stampErrorBrands(this, new.target); - } - /** - * Converts the error to a standard OAuth error response object. - */ - toResponseObject() { - const response = { - error: this.code, - error_description: this.message - }; - if (this.errorUri) response.error_uri = this.errorUri; - return response; - } - /** - * Creates an {@linkcode OAuthError} from an OAuth error response. - */ - static fromResponse(response) { - return new OAuthError(response.error, response.error_description ?? response.error, response.error_uri); - } -}; - -//#endregion -//#region ../core-internal/src/errors/sdkErrors.ts -/** -* Error codes for SDK errors (local errors that never cross the wire). -* Unlike {@linkcode ProtocolErrorCode} which uses numeric JSON-RPC codes, `SdkErrorCode` uses -* descriptive string values for better developer experience. -* -* These errors are thrown locally by the SDK and are never serialized as -* JSON-RPC error responses. -*/ -let src_CX2iR2pK_SdkErrorCode = /* @__PURE__ */ function(SdkErrorCode$1) { - /** Transport is not connected */ - SdkErrorCode$1["NotConnected"] = "NOT_CONNECTED"; - /** Transport is already connected */ - SdkErrorCode$1["AlreadyConnected"] = "ALREADY_CONNECTED"; - /** Protocol is not initialized */ - SdkErrorCode$1["NotInitialized"] = "NOT_INITIALIZED"; - /** Required capability is not supported by the remote side */ - SdkErrorCode$1["CapabilityNotSupported"] = "CAPABILITY_NOT_SUPPORTED"; - /** Request timed out waiting for response */ - SdkErrorCode$1["RequestTimeout"] = "REQUEST_TIMEOUT"; - /** Connection was closed */ - SdkErrorCode$1["ConnectionClosed"] = "CONNECTION_CLOSED"; - /** Failed to send message */ - SdkErrorCode$1["SendFailed"] = "SEND_FAILED"; - /** Response result failed local schema validation */ - SdkErrorCode$1["InvalidResult"] = "INVALID_RESULT"; - /** - * The response carried a `resultType` discriminator (protocol revision - * 2026-07-28) naming a result kind this client cannot consume yet, e.g. - * `input_required`. The kind is carried in `data.resultType`. - */ - SdkErrorCode$1["UnsupportedResultType"] = "UNSUPPORTED_RESULT_TYPE"; - /** - * The multi-round-trip auto-fulfilment driver exhausted its round cap - * (`inputRequired.maxRounds`) without the server returning a complete - * result. `data.rounds` carries the cap that was hit and - * `data.lastResult` carries the last `input_required` payload received - * (`{ inputRequests, requestState? }`), so callers can inspect or resume - * the flow manually. - */ - SdkErrorCode$1["InputRequiredRoundsExceeded"] = "INPUT_REQUIRED_ROUNDS_EXCEEDED"; - /** - * The auto-aggregating no-`cursor` `listTools()` / `listPrompts()` / - * `listResources()` / `listResourceTemplates()` walk hit the - * `ClientOptions.listMaxPages` cap without the server's pagination - * converging. `data.method` carries the list verb and - * `data.listMaxPages` the cap that was hit; raise the cap or fall back to - * explicit per-page `{ cursor }` calls. - */ - SdkErrorCode$1["ListPaginationExceeded"] = "LIST_PAGINATION_EXCEEDED"; - /** - * The spec method being sent does not exist on the negotiated protocol - * version's wire era (e.g. `tasks/get` toward a 2026-07-28 peer, or - * `server/discover` toward a 2025-era peer). Raised locally, before - * anything reaches the transport. The method and era are carried in - * `data.method` / `data.era`. - */ - SdkErrorCode$1["MethodNotSupportedByProtocolVersion"] = "METHOD_NOT_SUPPORTED_BY_PROTOCOL_VERSION"; - /** - * Protocol-era negotiation at connect time failed without producing either a - * usable modern (2026-07-28+) era or a definitive legacy fallback signal — - * e.g. the negotiation mode forbids falling back (`pin`), the probe hit a - * network failure, or the server answered the probe with a 5xx (a typed - * connect error, never an era verdict). - * - * Negotiation-phase only: this code is never used once an era is - * established. Auth walls never carry it: a 401/403 rejecting the probe - * uses {@linkcode ClientHttpAuthentication} / {@linkcode ClientHttpForbidden} - * instead, so era-recovery flows keyed on this code (e.g. cached-verdict - * gateways) can never persist a verdict for an unauthorized exchange. - */ - SdkErrorCode$1["EraNegotiationFailed"] = "ERA_NEGOTIATION_FAILED"; - SdkErrorCode$1["ClientHttpNotImplemented"] = "CLIENT_HTTP_NOT_IMPLEMENTED"; - /** - * HTTP 401 authentication failure: the transport's re-auth retry still got - * 401 (`Server returned 401 after re-authentication`), or the version - * negotiation probe was rejected 401 with no `authProvider` configured - * (`Version negotiation failed: the server requires authorization (HTTP 401)`). - * Carried on an {@linkcode SdkHttpError} with `status: 401`. - */ - SdkErrorCode$1["ClientHttpAuthentication"] = "CLIENT_HTTP_AUTHENTICATION"; - /** - * HTTP 403 denial: the step-up re-authorization retry limit was reached, - * or the version negotiation probe was rejected 403 - * (`Version negotiation failed: the server denied access (HTTP 403)`). - * Carried on an {@linkcode SdkHttpError} with `status: 403`. - */ - SdkErrorCode$1["ClientHttpForbidden"] = "CLIENT_HTTP_FORBIDDEN"; - SdkErrorCode$1["ClientHttpUnexpectedContent"] = "CLIENT_HTTP_UNEXPECTED_CONTENT"; - SdkErrorCode$1["ClientHttpFailedToOpenStream"] = "CLIENT_HTTP_FAILED_TO_OPEN_STREAM"; - SdkErrorCode$1["ClientHttpFailedToTerminateSession"] = "CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION"; - return SdkErrorCode$1; -}({}); -/** -* SDK errors are local errors that never cross the wire. -* They are distinct from {@linkcode ProtocolError} which represents JSON-RPC protocol errors -* that are serialized and sent as error responses. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkError_basicUsage" -* try { -* // Throwing an SDK error -* throw new SdkError(SdkErrorCode.NotConnected, 'Transport is not connected'); -* } catch (error) { -* // Checking error type by code -* if (error instanceof SdkError && error.code === SdkErrorCode.RequestTimeout) { -* // Handle timeout -* } -* } -* ``` -*/ -var src_CX2iR2pK_SdkError = class extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "SdkError"; - stampErrorBrands(this, new.target); - } -}; -/** -* An {@linkcode SdkError} subclass for HTTP transport failures. -* -* Thrown by the streamable HTTP transport when the server responds with a -* non-OK status code. Narrows {@linkcode SdkError.data | data} to -* {@linkcode SdkHttpErrorData} so consumers can inspect the HTTP status -* without unsafe casting. -* -* @example -* ```ts source="./sdkErrors.examples.ts#SdkHttpError_basicUsage" -* if (error instanceof SdkHttpError) { -* console.log(error.status); // number -* console.log(error.statusText); // string | undefined -* } -* ``` -*/ -var SdkHttpError = class extends src_CX2iR2pK_SdkError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.SdkHttpError" }); - } - constructor(code, message, data) { - super(code, message, data); - this.name = "SdkHttpError"; - } - get status() { - return this.data.status; - } - get statusText() { - return this.data.statusText; - } -}; - -//#endregion -//#region ../core-internal/src/shared/authUtils.ts -/** -* Utilities for handling OAuth resource URIs. -*/ -/** -* Converts a server URL to a resource URL by removing the fragment. -* {@link https://datatracker.ietf.org/doc/html/rfc8707#section-2 | RFC 8707 section 2} -* states that resource URIs "MUST NOT include a fragment component". -* Keeps everything else unchanged (scheme, domain, port, path, query). -*/ -function resourceUrlFromServerUrl(url) { - const resourceURL = typeof url === "string" ? new URL(url) : new URL(url.href); - resourceURL.hash = ""; - return resourceURL; -} -/** -* Checks if a requested resource URL matches a configured resource URL. -* A requested resource matches if it has the same scheme, domain, port, -* and its path starts with the configured resource's path. -* -* @param options - The options object -* @param options.requestedResource - The resource URL being requested -* @param options.configuredResource - The resource URL that has been configured -* @returns true if the requested resource matches the configured resource, false otherwise -*/ -function checkResourceAllowed({ requestedResource, configuredResource }) { - const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href); - const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href); - if (requested.origin !== configured.origin) return false; - if (requested.pathname.length < configured.pathname.length) return false; - const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/"; - const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/"; - return requestedPath.startsWith(configuredPath); -} - -//#endregion -//#region ../core-internal/src/shared/clientCapabilityRequirements.ts -/** -* Inbound request methods whose processing structurally requires a client -* capability, keyed by method, valued by the capabilities required. -* -* Currently empty: none of the request methods served on the 2026-07-28 -* registry unconditionally requires a client capability. Entries appear here -* when such methods exist — for example requests whose handling embeds -* elicitation or sampling input requests (the input-request engine), or -* opt-in subscription delivery. Handler-conditional requirements (a specific -* tool that needs sampling) are not expressible as a static method table and -* are enforced at the point the requirement arises instead. -*/ -const REQUIRED_CLIENT_CAPABILITIES_BY_METHOD = (/* unused pure expression or super */ null && ({})); -/** -* The client capabilities a request method structurally requires, or -* `undefined` when the method has no static requirement. -*/ -function src_CX2iR2pK_requiredClientCapabilitiesForRequest(method) { - return Object.hasOwn(REQUIRED_CLIENT_CAPABILITIES_BY_METHOD, method) ? REQUIRED_CLIENT_CAPABILITIES_BY_METHOD[method] : void 0; -} -function isPlainObject$7(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Whether a required nested member counts as declared even though it is not -* spelled out: a bare `elicitation: {}` declaration (no mode sub-capability at -* all) is read as form support — the pre-mode (2025) meaning of a bare -* declaration — so an `elicitation.form` requirement treats it as satisfied. -* Declaring any mode explicitly (for example `elicitation: { url: {} }`) -* removes the implication. -*/ -function isImpliedCapabilityMember(capability, member, declaredValue) { - return capability === "elicitation" && member === "form" && declaredValue["form"] === void 0 && declaredValue["url"] === void 0; -} -/** -* The client capabilities an embedded multi-round-trip input request requires -* (call site 2 — the outbound input-request leg): a server MUST NOT send an -* `inputRequests` kind the request's declared client capabilities do not -* cover. Returns `undefined` for entries whose method is not one of the -* embedded input-request kinds (those are a server bug handled separately, -* not a capability question). -* -* The requirement is mode-aware where the capability is: URL-mode elicitation -* requires `elicitation.url`; form-mode (or mode-omitted) elicitation requires -* `elicitation.form` (modes are sub-capabilities, and a server MUST NOT send a -* mode the client did not declare); sampling with `tools`/`toolChoice` -* requires `sampling.tools`. A bare `elicitation: {}` declaration satisfies -* the form requirement — see {@linkcode missingClientCapabilities}. -*/ -function requiredClientCapabilitiesForInputRequest(entry) { - switch (entry.method) { - case "elicitation/create": - if (entry.params?.["mode"] === "url") return { elicitation: { url: {} } }; - return { elicitation: { form: {} } }; - case "sampling/createMessage": { - const params = entry.params; - if (params !== void 0 && (params["tools"] !== void 0 || params["toolChoice"] !== void 0)) return { sampling: { tools: {} } }; - return { sampling: {} }; - } - case "roots/list": return { roots: {} }; - default: return; - } -} -/** -* Computes the subset of `required` client capabilities the client did not -* declare. Returns `undefined` when every required capability is declared; -* otherwise returns an object in the `ClientCapabilities` shape containing -* exactly the missing capabilities (suitable for -* `data.requiredCapabilities` on the `-32021` error). -* -* A capability counts as declared when its top-level key is present on the -* declared capabilities; when the requirement names nested members (for -* example `elicitation: { url: {} }`), each named member must also be present -* under the declared capability. One lenient reading applies: a bare -* `elicitation: {}` declaration (no mode sub-capability at all) counts as -* declaring `elicitation.form` — the pre-mode (2025) meaning of a bare -* declaration. An absent or empty `declared` value means -* nothing is declared — every required capability is missing (the structural -* clean-refusal posture for sessions with no per-request capability view). -*/ -function src_CX2iR2pK_missingClientCapabilities(required, declared) { - const missing = {}; - for (const [capability, requirement] of Object.entries(required)) { - if (requirement === void 0) continue; - const declaredValue = declared === void 0 ? void 0 : declared[capability]; - if (declaredValue === void 0) { - missing[capability] = requirement; - continue; - } - if (isPlainObject$7(requirement) && isPlainObject$7(declaredValue)) { - const missingMembers = {}; - for (const [member, memberRequirement] of Object.entries(requirement)) if (memberRequirement !== void 0 && declaredValue[member] === void 0 && !isImpliedCapabilityMember(capability, member, declaredValue)) missingMembers[member] = memberRequirement; - if (Object.keys(missingMembers).length > 0) missing[capability] = missingMembers; - } - } - return Object.keys(missing).length > 0 ? missing : void 0; -} - -//#endregion -//#region ../core-internal/src/shared/protocolEras.ts -/** -* The first protocol revision of the modern (2026-07-28) era. Revision identifiers -* are ISO dates, so lexicographic comparison orders them chronologically. -*/ -const FIRST_MODERN_PROTOCOL_VERSION = "2026-07-28"; -/** -* Modern-era protocol revisions this SDK can negotiate via `server/discover`. -* Deliberately separate from {@linkcode SUPPORTED_PROTOCOL_VERSIONS} (the legacy -* `initialize` list), so adding a revision here can never leak a modern version -* string into a 2025-era handshake. Internal — not part of the public API surface. -*/ -const src_CX2iR2pK_SUPPORTED_MODERN_PROTOCOL_VERSIONS = (/* unused pure expression or super */ null && ([FIRST_MODERN_PROTOCOL_VERSION])); -/** Whether the given protocol revision belongs to the modern (2026-07-28+) era. */ -function isModernProtocolVersion(version) { - return version >= FIRST_MODERN_PROTOCOL_VERSION; -} -/** The legacy-era (pre-2026-07-28) subset of a supported-versions list, in the list's own preference order. */ -function legacyProtocolVersions(versions) { - return versions.filter((version) => !isModernProtocolVersion(version)); -} -/** The modern-era (2026-07-28+) subset of a supported-versions list, in the list's own preference order. */ -function modernProtocolVersions(versions) { - return versions.filter((version) => isModernProtocolVersion(version)); -} - -//#endregion -//#region ../core-internal/src/wire/textFallback.ts -/** -* SEP-2106 §4.3 TextContent auto-append, era-agnostic, called from BOTH -* codecs' {@link WireCodec.projectCallToolResult}: when `structuredContent` -* is a non-object value (array/primitive/`null`) and the handler authored no -* `type:'text'` block, append `{type:'text', text: JSON.stringify(value)}`. -* Object-shaped (or absent) `structuredContent` returns the same reference. -* -* Leaf module: imported by both era codec modules, so it must NOT import from -* `./codec.js` (which value-imports the rev codecs at top level — that would -* make a runtime cycle and a TDZ hazard for entries that evaluate a rev codec -* module first). -*/ -function appendTextFallbackForNonObject(result) { - const sc = result.structuredContent; - if (sc === void 0) return result; - if (!(typeof sc !== "object" || sc === null || Array.isArray(sc))) return result; - if (result.content?.some((c) => c.type === "text") ?? false) return result; - return { - ...result, - content: [...result.content ?? [], { - type: "text", - text: JSON.stringify(sc) - }] - }; -} - -//#endregion -//#region ../core-internal/src/wire/resultFamilies.ts -/** -* Result-family keys that must never default into a `{content: []}` tools/call -* success. Shared by the 2025 wire-seam schema and server normalization. -* Leaf module (like `textFallback.ts`): imported by registry/server paths, so -* it must NOT import from `./codec.js` — that would close a runtime cycle. -*/ -const TOOL_RESULT_FOREIGN_FAMILY_KEYS = [ - "task", - "inputRequests", - "requestState" -]; -/** -* Single owner of the v1-parity ruling: a plain-object tool result without `content` (and -* without foreign-family keys) gains `content: []`. Shared by the 2025 wire seam and server-side handler normalization. -*/ -function normalizeContentlessToolResult(value) { - if (value === null || typeof value !== "object" || Array.isArray(value) || value.content !== void 0 || TOOL_RESULT_FOREIGN_FAMILY_KEYS.some((key) => key in value)) return value; - return { - ...value, - content: [] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/buildSchemas.ts -/** -* Complete frozen 2025-11-25 wire schemas. Self-contained — no imports from -* the public/neutral types/schemas.ts. The neutral layer is the public-API -* superset and is free to evolve (e.g., SEP-2106 widening); this file is the -* 2025 wire-parse contract (Q10-L2 byte-identity) and is BEHAVIOR-FROZEN. -* -* This is the era's complete frozen wire-parse contract — both the 2025-only -* delta (the deprecated task family, the era role unions) AND frozen copies of -* every era-shared shape (Tool, CallToolResult, Initialize*, ContentBlock, -* prompts/resources/completion/elicitation, …). The 2026-era codec -* (`wire/rev2026-07-28/`) is symmetrically self-contained in the same way. -* -* The 2025-only delta (the task message surface, restored types-only by #2248 -* for interop with task-capable 2025 peers) is parsed ONLY through this era's -* registry; the deprecated Task* schemas also live (marked `@deprecated`) in -* the neutral schema layer so the public types stay nameable without a -* cross-layer import — nameability is constant, runtime availability is -* version-keyed — but appear in no API signature. Q1 increment 2 — deletions -* are physical: the -* 2026-era REGISTRY has no Task* methods (its frozen building-block copies do -* carry the deprecated Task* sub-schemas by composition — soft contamination, -* tracked for anchor-exactness adjudication). -* -* The only cross-layer dependency is `import type { JSONObject, JSONValue }` -* from the neutral types barrel — pure structural type aliases with no parse -* behavior. No runtime schema is shared with the neutral layer. -*/ -function build$1() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** - * Metadata for associating messages with a task. - * Include this in the `_meta` field under the key `io.modelcontextprotocol/related-task`. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - /** - * Common params for any request. - */ - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** - * Common params for any task-augmented request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const RequestSchema$1 = schemas_object({ - method: schemas_string(), - params: BaseRequestParamsSchema$1.loose().optional() - }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const ResultSchema$1 = looseObject({ _meta: RequestMetaSchema$1.optional() }); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * A response that indicates success but carries no data. - */ - const EmptyResultSchema$1 = ResultSchema$1.strict(); - const CancelledNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - requestId: RequestIdSchema$1.optional(), - reason: schemas_string().optional() - }); - /** - * This notification can be sent by either side to indicate that it is cancelling a previously-issued request. - * - * The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished. - * - * This notification indicates that the result will be unused, so any associated processing SHOULD cease. - * - * A client MUST NOT attempt to cancel its {@linkcode InitializeRequest | initialize} request. - */ - const CancelledNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - /** - * Icon schema for use in {@link Tool | tools}, {@link Prompt | prompts}, {@link Resource | resources}, and {@link Implementation | implementations}. - */ - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - /** - * Base schema to add `icons` property. - * - */ - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - /** - * Base metadata interface for common properties across {@link Resource | resources}, {@link Tool | tools}, {@link Prompt | prompts}, and {@link Implementation | implementations}. - */ - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - /** - * Describes the name and version of an MCP implementation. - */ - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** - * Task capabilities for clients, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** - * Task capabilities for servers, indicating which request types support task creation. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - /** - * Capabilities a client may support. Known capabilities are defined here, in this schema, but this is not a closed set: any client can define its own, additional capabilities. - */ - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const InitializeRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ClientCapabilitiesSchema$1, - clientInfo: ImplementationSchema$1 - }); - /** - * This request is sent from the client to the server when it first connects, asking it to begin initialization. - */ - const InitializeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("initialize"), - params: InitializeRequestParamsSchema$1 - }); - /** - * Capabilities that a server may support. Known capabilities are defined here, in this schema, but this is not a closed set: any server can define its own, additional capabilities. - */ - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - /** - * After receiving an initialize request from the client, the server sends this response. - */ - const InitializeResultSchema$1 = ResultSchema$1.extend({ - protocolVersion: schemas_string(), - capabilities: ServerCapabilitiesSchema$1, - serverInfo: ImplementationSchema$1, - instructions: schemas_string().optional() - }); - /** - * This notification is sent from the client to the server after initialization has finished. - */ - const InitializedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/initialized"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * A ping, issued by either the server or the client, to check that the other party is still alive. The receiver must promptly respond, or else may be disconnected. - */ - const PingRequestSchema$1 = RequestSchema$1.extend({ - method: literal("ping"), - params: BaseRequestParamsSchema$1.optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - /** - * An out-of-band notification used to inform the receiver of a progress update for a long-running request. - * - * @category notifications/progress - */ - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const PaginatedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ cursor: CursorSchema$1.optional() }); - const PaginatedRequestSchema$1 = RequestSchema$1.extend({ params: PaginatedRequestParamsSchema$1.optional() }); - const PaginatedResultSchema$1 = ResultSchema$1.extend({ nextCursor: CursorSchema$1.optional() }); - /** - * The contents of a specific resource or sub-resource. - */ - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * Optional annotations providing clients additional context about a resource. - */ - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - /** - * A known resource that the server is capable of reading. - */ - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * A template description for resources available on the server. - */ - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of resources the server has. - */ - const ListResourcesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/list") }); - /** - * The server's response to a {@linkcode ListResourcesRequest | resources/list} request from the client. - */ - const ListResourcesResultSchema$1 = PaginatedResultSchema$1.extend({ resources: schemas_array(ResourceSchema$1) }); - /** - * Sent from the client to request a list of resource templates the server has. - */ - const ListResourceTemplatesRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("resources/templates/list") }); - /** - * The server's response to a {@linkcode ListResourceTemplatesRequest | resources/templates/list} request from the client. - */ - const ListResourceTemplatesResultSchema$1 = PaginatedResultSchema$1.extend({ resourceTemplates: schemas_array(ResourceTemplateSchema$1) }); - const ResourceRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ uri: schemas_string() }); - /** - * Parameters for a {@linkcode ReadResourceRequest | resources/read} request. - */ - const ReadResourceRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to the server, to read a specific resource URI. - */ - const ReadResourceRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/read"), - params: ReadResourceRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode ReadResourceRequest | resources/read} request from the client. - */ - const ReadResourceResultSchema$1 = ResultSchema$1.extend({ contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) }); - /** - * An optional notification from the server to the client, informing it that the list of resources it can read from has changed. This may be issued by servers without any previous subscription from the client. - */ - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const SubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request `resources/updated` notifications from the server whenever a particular resource changes. - */ - const SubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/subscribe"), - params: SubscribeRequestParamsSchema$1 - }); - const UnsubscribeRequestParamsSchema$1 = ResourceRequestParamsSchema$1; - /** - * Sent from the client to request cancellation of {@linkcode ResourceUpdatedNotification | resources/updated} notifications from the server. This should follow a previous {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const UnsubscribeRequestSchema$1 = RequestSchema$1.extend({ - method: literal("resources/unsubscribe"), - params: UnsubscribeRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ResourceUpdatedNotification | notifications/resources/updated} notification. - */ - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - /** - * A notification from the server to the client, informing it that a resource has changed and may need to be read again. This should only be sent if the client previously sent a {@linkcode SubscribeRequest | resources/subscribe} request. - */ - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - /** - * Describes an argument that a prompt can accept. - */ - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - /** - * A prompt or prompt template that the server offers. - */ - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - /** - * Sent from the client to request a list of prompts and prompt templates the server has. - */ - const ListPromptsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("prompts/list") }); - /** - * The server's response to a {@linkcode ListPromptsRequest | prompts/list} request from the client. - */ - const ListPromptsResultSchema$1 = PaginatedResultSchema$1.extend({ prompts: schemas_array(PromptSchema$1) }); - /** - * Parameters for a {@linkcode GetPromptRequest | prompts/get} request. - */ - const GetPromptRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }); - /** - * Used by the client to get a prompt provided by the server. - */ - const GetPromptRequestSchema$1 = RequestSchema$1.extend({ - method: literal("prompts/get"), - params: GetPromptRequestParamsSchema$1 - }); - /** - * Text provided to or from an LLM. - */ - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * An image provided to or from an LLM. - */ - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Audio content provided to or from an LLM. - */ - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A tool call request from an assistant (LLM). - * Represents the assistant's request to use a tool. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * The contents of a resource, embedded into a prompt or tool call result. - */ - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * A resource that the server is capable of reading, included in a prompt or tool call result. - * - * Note: resource links returned by tools are not guaranteed to appear in the results of {@linkcode ListResourcesRequest | resources/list} requests. - */ - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - /** - * A content block that can be used in prompts and tool results. - */ - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - /** - * Describes a message returned as part of a prompt. - */ - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - /** - * The server's response to a {@linkcode GetPromptRequest | prompts/get} request from the client. - */ - const GetPromptResultSchema$1 = ResultSchema$1.extend({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - /** - * An optional notification from the server to the client, informing it that the list of prompts it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Additional properties describing a `Tool` to clients. - * - * NOTE: all properties in {@linkcode ToolAnnotations} are **hints**. - * They are not guaranteed to provide a faithful description of - * tool behavior (including descriptive properties like `title`). - * - * Clients should never make tool use decisions based on `ToolAnnotations` - * received from untrusted servers. - */ - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - /** - * Execution-related properties for a tool. - */ - const ToolExecutionSchema$1 = schemas_object({ taskSupport: schemas_enum([ - "required", - "optional", - "forbidden" - ]).optional() }); - /** - * Definition for a tool the client can call. - */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()), - outputSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), JSONValueSchema$1).optional(), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - execution: ToolExecutionSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the client to request a list of tools the server has. - */ - const ListToolsRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tools/list") }); - /** - * The server's response to a {@linkcode ListToolsRequest | tools/list} request from the client. - */ - const ListToolsResultSchema$1 = PaginatedResultSchema$1.extend({ tools: schemas_array(ToolSchema$1) }); - /** - * The server's response to a tool call. - */ - const CallToolResultSchema$1 = ResultSchema$1.extend({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_record(schemas_string(), unknown()).optional(), - isError: schemas_boolean().optional() - }); - /** - * Parameters for a `tools/call` request. - */ - const CallToolRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Used by the client to invoke a tool provided by the server. - */ - const CallToolRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tools/call"), - params: CallToolRequestParamsSchema$1 - }); - /** - * An optional notification from the server to the client, informing it that the list of tools it offers has changed. This may be issued by servers without any previous subscription from the client. - */ - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * The severity of a log message. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * Parameters for a `logging/setLevel` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ level: LoggingLevelSchema$1 }); - /** - * A request from the client to the server, to enable or adjust logging. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const SetLevelRequestSchema$1 = RequestSchema$1.extend({ - method: literal("logging/setLevel"), - params: SetLevelRequestParamsSchema$1 - }); - /** - * Parameters for a `notifications/message` notification. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - /** - * Notification of a log message passed from server to client. If no `logging/setLevel` request has been sent from the client, the server MAY decide which messages to send automatically. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to stderr logging - * (STDIO servers) or OpenTelemetry. - */ - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - /** - * Hints to use for model selection. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - /** - * The server's preferences for model selection, requested of the client during sampling. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - /** - * Controls tool usage behavior in sampling requests. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - /** - * The result of a tool execution, provided by the user (server). - * Represents the outcome of invoking a tool requested via `ToolUseContent`. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string().describe("The unique identifier for the corresponding tool call."), - content: schemas_array(ContentBlockSchema$1), - structuredContent: schemas_object({}).loose().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Basic content types for sampling responses (without tool use). - * Used for backwards-compatible {@linkcode CreateMessageResult} when tools are not used. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingContentSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1 - ]); - /** - * Content block types allowed in sampling messages. - * This includes text, image, audio, tool use requests, and tool results. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageContentBlockSchema$1 = discriminatedUnion("type", [ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** - * Describes a message issued to or received from an LLM API. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Parameters for a `sampling/createMessage` request. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** - * A request from the server to sample an LLM via the client. The client has full discretion over which model to select. The client should also inform the user before beginning sampling, to allow them to inspect the request (human in the loop) and decide whether to approve it. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageRequestSchema$1 = RequestSchema$1.extend({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request from the server. - * This is the backwards-compatible version that returns single content (no arrays). - * Used when the request does not include tools. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens" - ]).or(schemas_string())), - role: RoleSchema$1, - content: SamplingContentSchema$1 - }); - /** - * The client's response to a `sampling/create_message` request when tools were provided. - * This version supports array content for tool use flows. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to calling LLM - * provider APIs directly. - */ - const CreateMessageResultWithToolsSchema$1 = ResultSchema$1.extend({ - model: schemas_string(), - stopReason: schemas_optional(schemas_enum([ - "endTurn", - "stopSequence", - "maxTokens", - "toolUse" - ]).or(schemas_string())), - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]) - }); - /** - * Primitive schema definition for boolean fields. - */ - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - /** - * Primitive schema definition for string fields. - */ - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - /** - * Primitive schema definition for number fields. - */ - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - /** - * Schema for single-selection enumeration without display titles for options. - */ - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - /** - * Schema for single-selection enumeration with display titles for each option. - */ - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - /** - * Use {@linkcode TitledSingleSelectEnumSchema} instead. - * This interface will be removed in a future version. - */ - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - /** - * Schema for multiple-selection enumeration without display titles for options. - */ - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Schema for multiple-selection enumeration with display titles for each option. - */ - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - /** - * Combined schema for multiple-selection enumeration - */ - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - /** - * Primitive schema definition for enum fields. - */ - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - /** - * Union of all primitive schema definitions. - */ - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - /** - * Parameters for an `elicitation/create` request for form-based elicitation. - */ - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - /** - * Parameters for an {@linkcode ElicitRequest | elicitation/create} request for URL-based elicitation. - */ - const ElicitRequestURLParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("url"), - message: schemas_string(), - elicitationId: schemas_string(), - url: schemas_string().url() - }); - /** - * The parameters for a request to elicit additional information from the user via the client. - */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** - * A request from the server to elicit user input via the client. - * The client should present the message and form fields to the user (form mode) - * or navigate to a URL (URL mode). - */ - const ElicitRequestSchema$1 = RequestSchema$1.extend({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** - * Parameters for a {@linkcode ElicitationCompleteNotification | notifications/elicitation/complete} notification. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ elicitationId: schemas_string() }); - /** - * A notification from the server to the client, informing it of a completion of an out-of-band elicitation request. - * - * @category notifications/elicitation/complete - */ - const ElicitationCompleteNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/elicitation/complete"), - params: ElicitationCompleteNotificationParamsSchema$1 - }); - /** - * The client's response to an {@linkcode ElicitRequest | elicitation/create} request from the server. - */ - const ElicitResultSchema$1 = ResultSchema$1.extend({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: preprocess((val) => val === null ? void 0 : val, schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional()) - }); - /** - * A reference to a resource or resource template definition. - */ - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - /** - * Identifies a prompt. - */ - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - /** - * Parameters for a {@linkcode CompleteRequest | completion/complete} request. - */ - const CompleteRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }); - /** - * A request from the client to the server, to ask for completion options. - */ - const CompleteRequestSchema$1 = RequestSchema$1.extend({ - method: literal("completion/complete"), - params: CompleteRequestParamsSchema$1 - }); - /** - * The server's response to a {@linkcode CompleteRequest | completion/complete} request - */ - const CompleteResultSchema$1 = ResultSchema$1.extend({ completion: looseObject({ - values: schemas_array(schemas_string()).max(100), - total: schemas_optional(schemas_number().int()), - hasMore: schemas_optional(schemas_boolean()) - }) }); - /** - * Represents a root directory or file that the server can operate on. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** - * Sent from the server to request a list of root URIs from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsRequestSchema$1 = RequestSchema$1.extend({ - method: literal("roots/list"), - params: BaseRequestParamsSchema$1.optional() - }); - /** - * The client's response to a `roots/list` request from the server. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const ListRootsResultSchema$1 = ResultSchema$1.extend({ roots: schemas_array(RootSchema$1) }); - /** - * A notification from the client to the server, informing it that the list of roots has changed. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577); remains - * in the specification for at least twelve months. Migrate to passing paths via - * tool parameters, resource URIs, or configuration. - */ - const RootsListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/roots/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - /** - * Task creation parameters, used to ask that the server create a task to represent a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskCreationParamsSchema$1 = looseObject({ - ttl: schemas_number().optional(), - pollInterval: schemas_number().optional() - }); - /** - * The status of a task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusSchema$1 = schemas_enum([ - "working", - "input_required", - "completed", - "failed", - "cancelled" - ]); - /** - * A pollable state object associated with a request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskSchema$1 = schemas_object({ - taskId: schemas_string(), - status: TaskStatusSchema$1, - ttl: schemas_union([schemas_number(), schemas_null()]), - createdAt: schemas_string(), - lastUpdatedAt: schemas_string(), - pollInterval: schemas_optional(schemas_number()), - statusMessage: schemas_optional(schemas_string()) - }); - /** - * Result returned when a task is created, containing the task data wrapped in a `task` field. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CreateTaskResultSchema$1 = ResultSchema$1.extend({ task: TaskSchema$1 }); - /** - * Parameters for task status notification. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationParamsSchema$1 = NotificationsParamsSchema$1.merge(TaskSchema$1); - /** - * A notification sent when a task's status changes. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const TaskStatusNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tasks/status"), - params: TaskStatusNotificationParamsSchema$1 - }); - /** - * A request to get the state of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/get"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a {@linkcode GetTaskRequest | tasks/get} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskResultSchema$1 = ResultSchema$1.merge(TaskSchema$1); - /** - * A request to get the result of a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/result"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - /** - * The response to a `tasks/result` request. - * The structure matches the result type of the original request. - * For example, a {@linkcode CallToolRequest | tools/call} task would return the `CallToolResult` structure. - * - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const GetTaskPayloadResultSchema$1 = ResultSchema$1.loose(); - /** - * A request to list tasks. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksRequestSchema$1 = PaginatedRequestSchema$1.extend({ method: literal("tasks/list") }); - /** - * The response to a {@linkcode ListTasksRequest | tasks/list} request. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const ListTasksResultSchema$1 = PaginatedResultSchema$1.extend({ tasks: schemas_array(TaskSchema$1) }); - /** - * A request to cancel a specific task. - * - * @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. - */ - const CancelTaskRequestSchema$1 = RequestSchema$1.extend({ - method: literal("tasks/cancel"), - params: BaseRequestParamsSchema$1.extend({ taskId: schemas_string() }) - }); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - RequestSchema: RequestSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - ResultSchema: ResultSchema$1, - RequestIdSchema: RequestIdSchema$1, - EmptyResultSchema: EmptyResultSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - InitializeRequestParamsSchema: InitializeRequestParamsSchema$1, - InitializeRequestSchema: InitializeRequestSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - InitializeResultSchema: InitializeResultSchema$1, - InitializedNotificationSchema: InitializedNotificationSchema$1, - PingRequestSchema: PingRequestSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - PaginatedRequestParamsSchema: PaginatedRequestParamsSchema$1, - PaginatedRequestSchema: PaginatedRequestSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - RoleSchema: RoleSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ResourceRequestParamsSchema: ResourceRequestParamsSchema$1, - ReadResourceRequestParamsSchema: ReadResourceRequestParamsSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - SubscribeRequestParamsSchema: SubscribeRequestParamsSchema$1, - SubscribeRequestSchema: SubscribeRequestSchema$1, - UnsubscribeRequestParamsSchema: UnsubscribeRequestParamsSchema$1, - UnsubscribeRequestSchema: UnsubscribeRequestSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptRequestParamsSchema: GetPromptRequestParamsSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolExecutionSchema: ToolExecutionSchema$1, - ToolSchema: ToolSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - CallToolRequestParamsSchema: CallToolRequestParamsSchema$1, - CallToolRequestSchema: CallToolRequestSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - SetLevelRequestParamsSchema: SetLevelRequestParamsSchema$1, - SetLevelRequestSchema: SetLevelRequestSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingContentSchema: SamplingContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema: CreateMessageResultWithToolsSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - ElicitationCompleteNotificationParamsSchema: ElicitationCompleteNotificationParamsSchema$1, - ElicitationCompleteNotificationSchema: ElicitationCompleteNotificationSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - CompleteRequestParamsSchema: CompleteRequestParamsSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - RootSchema: RootSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - RootsListChangedNotificationSchema: RootsListChangedNotificationSchema$1, - TaskCreationParamsSchema: TaskCreationParamsSchema$1, - TaskStatusSchema: TaskStatusSchema$1, - TaskSchema: TaskSchema$1, - CreateTaskResultSchema: CreateTaskResultSchema$1, - TaskStatusNotificationParamsSchema: TaskStatusNotificationParamsSchema$1, - TaskStatusNotificationSchema: TaskStatusNotificationSchema$1, - GetTaskRequestSchema: GetTaskRequestSchema$1, - GetTaskResultSchema: GetTaskResultSchema$1, - GetTaskPayloadRequestSchema: GetTaskPayloadRequestSchema$1, - GetTaskPayloadResultSchema: GetTaskPayloadResultSchema$1, - ListTasksRequestSchema: ListTasksRequestSchema$1, - ListTasksResultSchema: ListTasksResultSchema$1, - CancelTaskRequestSchema: CancelTaskRequestSchema$1, - CancelTaskResultSchema: ResultSchema$1.merge(TaskSchema$1), - ClientRequestSchema: schemas_union([ - PingRequestSchema$1, - InitializeRequestSchema$1, - CompleteRequestSchema$1, - SetLevelRequestSchema$1, - GetPromptRequestSchema$1, - ListPromptsRequestSchema$1, - ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema$1, - SubscribeRequestSchema$1, - UnsubscribeRequestSchema$1, - CallToolRequestSchema$1, - ListToolsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ClientNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - InitializedNotificationSchema$1, - RootsListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1 - ]), - ClientResultSchema: schemas_union([ - EmptyResultSchema$1, - CreateMessageResultSchema$1, - CreateMessageResultWithToolsSchema$1, - ElicitResultSchema$1, - ListRootsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - ServerRequestSchema: schemas_union([ - PingRequestSchema$1, - CreateMessageRequestSchema$1, - ElicitRequestSchema$1, - ListRootsRequestSchema$1, - GetTaskRequestSchema$1, - GetTaskPayloadRequestSchema$1, - ListTasksRequestSchema$1, - CancelTaskRequestSchema$1 - ]), - ServerNotificationSchema: schemas_union([ - CancelledNotificationSchema$1, - ProgressNotificationSchema$1, - LoggingMessageNotificationSchema$1, - ResourceUpdatedNotificationSchema$1, - ResourceListChangedNotificationSchema$1, - ToolListChangedNotificationSchema$1, - PromptListChangedNotificationSchema$1, - TaskStatusNotificationSchema$1, - ElicitationCompleteNotificationSchema$1 - ]), - ServerResultSchema: schemas_union([ - EmptyResultSchema$1, - InitializeResultSchema$1, - CompleteResultSchema$1, - GetPromptResultSchema$1, - ListPromptsResultSchema$1, - ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema$1, - CallToolResultSchema$1, - ListToolsResultSchema$1, - GetTaskResultSchema$1, - ListTasksResultSchema$1, - CreateTaskResultSchema$1 - ]), - CallToolResultWireSchema: unknown().superRefine((value, ctx) => { - if (typeof value !== "object" || value === null || Array.isArray(value) || value.content !== void 0) return; - for (const key of TOOL_RESULT_FOREIGN_FAMILY_KEYS) if (key in value) { - ctx.addIssue({ - code: "custom", - message: `content is required when the body carries '${key}' — another result family cannot default into an empty tools/call success` - }); - return; - } - }).transform(normalizeContentlessToolResult).pipe(CallToolResultSchema$1) - }; -} -let memo$1; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2025() { - return memo$1 ??= build$1(); -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/legacyWrap.ts -/** -* SEP-2106 legacy `outputSchema` wrap helpers (2025-era projection only). -* -* The neutral / 2026-07-28 model lets a tool's `outputSchema` carry any JSON -* Schema root. The 2025-11-25 wire shape requires `type:'object'` at the root, -* so when an era-blind handler advertises a non-object root, the 2025 codec's -* `encodeResult('tools/list', …)` projects it down to -* `{type:'object', properties:{result:}, required:['result']}`, and -* `projectCallToolResult` wraps the matching `structuredContent` as -* `{result:}`. The 2026 codec's projections are the identity. -* -* These helpers are wire-layer property — they exist so the projection can -* live behind {@link WireCodec.encodeResult} / {@link WireCodec.projectCallToolResult} -* and never be re-derived in shared/ or server-side code. -*/ -/** -* Whether a JSON Schema's root is non-object: either an explicit non-object -* `type`, or a typeless root such as `{anyOf:[…]}`. Object-shaped typeless -* roots that the schema-conversion layer can prove are objects are stamped -* `type:'object'` upstream, so they reach this predicate as object roots. -*/ -function isNonObjectJsonSchemaRoot(json) { - return json["type"] !== "object"; -} -/** -* Keyword-position keys whose values are instance data (not subschemas). A -* `{$ref:…}` appearing inside one is a literal value, not a JSON Pointer to -* rewrite. Only consulted when the current object is in keyword position — -* a PROPERTY named `default`/`const` (under `properties`/`$defs`/…) is a name -* position whose value IS a subschema and is recursed into. -*/ -const REF_REWRITE_DATA_POSITION_KEYS = new Set([ - "const", - "enum", - "default", - "examples" -]); -/** -* Keyword-position keys whose value is a name→subschema map. Entries inside -* such a map are in NAME position: their keys are author-chosen property -* names (which may collide with JSON Schema keywords), their values are -* subschemas to recurse into. -*/ -const REF_REWRITE_NAME_MAP_KEYS = new Set([ - "properties", - "patternProperties", - "$defs", - "definitions", - "dependentSchemas", - "dependencies" -]); -/** -* Whether a subtree's `$id` establishes a new resolution base. A fragment-only -* `$id` (`"#item"`, the draft-07/06 spelling of 2020-12's `$anchor`) does not -* change the RFC 3986 base URI — same-document pointers inside still resolve -* against the document root and must be rewritten. -*/ -function establishesNewBase(id) { - return id !== void 0 && !(typeof id === "string" && id.startsWith("#")); -} -/** -* Wrap a non-object output schema in the 2025-era envelope: -* `{type:'object', properties:{result:}, required:['result']}`. -* -* Same-document `$ref` / `$dynamicRef` JSON Pointers inside the natural schema -* (e.g. `#/properties/foo` produced by zod for de-duplicated/recursive types) -* are rewritten to account for the new `#/properties/result` root: bare `#` → -* `#/properties/result`, `#/…` → `#/properties/result/…`. Cross-document refs -* (anything not starting with `#`) are left untouched. -* -* The rewrite is position-aware: data-valued keywords -* (`const`/`enum`/`default`/`examples`) in keyword position are NOT descended -* into; the same names appearing as property names under -* `properties`/`patternProperties`/`$defs`/`definitions`/`dependentSchemas`/ -* `dependencies` ARE descended into (they're subschemas). The rewrite is also -* `$id`-scoped: if the natural root carries a base-establishing `$id` no -* pointer is rewritten (same-document refs inside resolve against the embedded -* `$id` base, not the wrapper root), and any subtree that establishes its own -* `$id` is left untouched for the same reason. Fragment-only `$id` (`"#item"`, -* draft-07's anchor spelling) does not establish a base and IS descended into. -*/ -function wrapOutputSchemaForLegacy(natural) { - const $schema = typeof natural["$schema"] === "string" ? natural["$schema"] : void 0; - if (establishesNewBase(natural["$id"])) return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: natural }, - required: ["result"] - }; - const convertRecursiveRefs = declares2019Dialect(natural["$schema"]) && natural["$recursiveAnchor"] !== true; - const rewriteRefs = (node, parentIsNameMap) => { - if (Array.isArray(node)) return node.map((item) => rewriteRefs(item, false)); - if (node === null || typeof node !== "object") return node; - if (!parentIsNameMap && establishesNewBase(node["$id"])) return node; - const out = {}; - let convertedRecursion = false; - for (const [k, v] of Object.entries(node)) if (parentIsNameMap) out[k] = rewriteRefs(v, false); - else if ((k === "$ref" || k === "$dynamicRef") && typeof v === "string") out[k] = v === "#" ? "#/properties/result" : v.startsWith("#/") ? `#/properties/result${v.slice(1)}` : v; - else if (k === "$recursiveRef" && v === "#" && convertRecursiveRefs) convertedRecursion = true; - else if (REF_REWRITE_DATA_POSITION_KEYS.has(k)) out[k] = v; - else if (REF_REWRITE_NAME_MAP_KEYS.has(k)) out[k] = rewriteRefs(v, true); - else out[k] = rewriteRefs(v, false); - if (convertedRecursion) if ("$ref" in out) out["allOf"] = [...Array.isArray(out["allOf"]) ? out["allOf"] : [], { $ref: "#/properties/result" }]; - else out["$ref"] = "#/properties/result"; - return out; - }; - return { - ...$schema !== void 0 && { $schema }, - type: "object", - properties: { result: rewriteRefs(natural, false) }, - required: ["result"] - }; -} - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/registry.ts -const requestMethodKeys$1 = { - ping: null, - initialize: null, - "completion/complete": null, - "logging/setLevel": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "resources/subscribe": null, - "resources/unsubscribe": null, - "tools/call": null, - "tools/list": null, - "tasks/get": null, - "tasks/result": null, - "tasks/list": null, - "tasks/cancel": null, - "sampling/createMessage": null, - "elicitation/create": null, - "roots/list": null -}; -const notificationMethodKeys$1 = { - "notifications/cancelled": null, - "notifications/progress": null, - "notifications/initialized": null, - "notifications/roots/list_changed": null, - "notifications/tasks/status": null, - "notifications/message": null, - "notifications/resources/updated": null, - "notifications/resources/list_changed": null, - "notifications/tools/list_changed": null, - "notifications/prompts/list_changed": null, - "notifications/elicitation/complete": null -}; -const resultMethodKeys = { - ping: null, - initialize: null, - "completion/complete": null, - "logging/setLevel": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "resources/subscribe": null, - "resources/unsubscribe": null, - "tools/call": null, - "tools/list": null, - "sampling/createMessage": null, - "elicitation/create": null, - "roots/list": null -}; -let maps$1; -function registryMaps() { - if (maps$1) return maps$1; - const s = buildSchemas2025(); - maps$1 = { - requestSchemas: { - ping: s.PingRequestSchema, - initialize: s.InitializeRequestSchema, - "completion/complete": s.CompleteRequestSchema, - "logging/setLevel": s.SetLevelRequestSchema, - "prompts/get": s.GetPromptRequestSchema, - "prompts/list": s.ListPromptsRequestSchema, - "resources/list": s.ListResourcesRequestSchema, - "resources/templates/list": s.ListResourceTemplatesRequestSchema, - "resources/read": s.ReadResourceRequestSchema, - "resources/subscribe": s.SubscribeRequestSchema, - "resources/unsubscribe": s.UnsubscribeRequestSchema, - "tools/call": s.CallToolRequestSchema, - "tools/list": s.ListToolsRequestSchema, - "tasks/get": s.GetTaskRequestSchema, - "tasks/result": s.GetTaskPayloadRequestSchema, - "tasks/list": s.ListTasksRequestSchema, - "tasks/cancel": s.CancelTaskRequestSchema, - "sampling/createMessage": s.CreateMessageRequestSchema, - "elicitation/create": s.ElicitRequestSchema, - "roots/list": s.ListRootsRequestSchema - }, - notificationSchemas: { - "notifications/cancelled": s.CancelledNotificationSchema, - "notifications/progress": s.ProgressNotificationSchema, - "notifications/initialized": s.InitializedNotificationSchema, - "notifications/roots/list_changed": s.RootsListChangedNotificationSchema, - "notifications/tasks/status": s.TaskStatusNotificationSchema, - "notifications/message": s.LoggingMessageNotificationSchema, - "notifications/resources/updated": s.ResourceUpdatedNotificationSchema, - "notifications/resources/list_changed": s.ResourceListChangedNotificationSchema, - "notifications/tools/list_changed": s.ToolListChangedNotificationSchema, - "notifications/prompts/list_changed": s.PromptListChangedNotificationSchema, - "notifications/elicitation/complete": s.ElicitationCompleteNotificationSchema - }, - resultSchemas: { - ping: s.EmptyResultSchema, - initialize: s.InitializeResultSchema, - "completion/complete": s.CompleteResultSchema, - "logging/setLevel": s.EmptyResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "resources/subscribe": s.EmptyResultSchema, - "resources/unsubscribe": s.EmptyResultSchema, - "tools/call": s.CallToolResultWireSchema, - "tools/list": s.ListToolsResultSchema, - "sampling/createMessage": s.CreateMessageResultWithToolsSchema, - "elicitation/create": s.ElicitResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps$1; -} -/** -* Forces the lazy registry maps (and, through them, the era's schema memo). -* Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmRegistryMaps2025() { - registryMaps(); -} -/** The 2025-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2025(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys$1, method); -} -/** The 2025-era notification-method set. */ -function hasNotificationMethod2025(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys$1, method); -} -/** Result-map membership: exactly the era's typed-method subset (no task entries, no 2026-only methods). */ -function hasResultMethod(method) { - return Object.prototype.hasOwnProperty.call(resultMethodKeys, method); -} -function getResultSchema(method) { - return hasResultMethod(method) ? registryMaps().resultSchemas[method] : void 0; -} -function getRequestSchema(method) { - return hasRequestMethod2025(method) ? registryMaps().requestSchemas[method] : void 0; -} -function getNotificationSchema(method) { - return hasNotificationMethod2025(method) ? registryMaps().notificationSchemas[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2025RequestMethods = Object.keys(requestMethodKeys$1); -const rev2025NotificationMethods = Object.keys(notificationMethodKeys$1); - -//#endregion -//#region ../core-internal/src/wire/rev2025-11-25/codec.ts -function isPlainObject$6(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState$1(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA$1 = { - ok: false, - reason: "not-in-era" -}; -/** Whether a `tools/list` entry advertises a non-object `outputSchema` root that needs the SEP-2106 legacy wrap. */ -function toolNeedsLegacyWrap(t) { - return isPlainObject$6(t) && isPlainObject$6(t["outputSchema"]) && isNonObjectJsonSchemaRoot(t["outputSchema"]); -} -/** The wire→neutral trust boundary: a decoded 2025-era wire result is adopted as the neutral `Result` here (the module's single deliberate assertion). */ -function toNeutralResult(value) { - return value; -} -const rev2025Codec = { - era: "2025-11-25", - hasRequestMethod: hasRequestMethod2025, - hasNotificationMethod: hasNotificationMethod2025, - validateRequest: (method, raw) => triState$1(getRequestSchema(method), raw), - validateResult: (method, raw) => triState$1(getResultSchema(method), raw), - validateNotification: (method, raw) => triState$1(getNotificationSchema(method), raw), - hasInputRequestMethod: () => false, - validateInputRequest: () => NOT_IN_ERA$1, - validateInputResponse: () => NOT_IN_ERA$1, - samplingResultVariant: ((hasTools, raw) => { - const s = buildSchemas2025(); - return triState$1(hasTools ? s.CreateMessageResultWithToolsSchema : s.CreateMessageResultSchema, raw); - }), - outboundEnvelope: (_material) => void 0, - validateEnvelopeMeta: (_meta) => [], - projectCallToolResult(result, advertisedOutputSchema) { - const withText = appendTextFallbackForNonObject(result); - const sc = withText.structuredContent; - if (sc === void 0) return withText; - const valueIsNonObject = typeof sc !== "object" || sc === null || Array.isArray(sc); - const schemaWrapped = advertisedOutputSchema !== void 0 && isNonObjectJsonSchemaRoot(advertisedOutputSchema); - if (!valueIsNonObject && !schemaWrapped) return withText; - return { - ...withText, - structuredContent: { result: sc } - }; - }, - decodeResult(_method, raw) { - if (isPlainObject$6(raw) && "resultType" in raw) { - const stripped = { ...raw }; - delete stripped["resultType"]; - return { - kind: "complete", - result: toNeutralResult(stripped) - }; - } - return { - kind: "complete", - result: toNeutralResult(raw) - }; - }, - encodeResult(method, result) { - if (method !== "tools/list") return result; - const tools = result.tools; - if (!Array.isArray(tools) || !tools.some((t) => toolNeedsLegacyWrap(t))) return result; - return { - ...result, - tools: tools.map((t) => toolNeedsLegacyWrap(t) ? { - ...t, - outputSchema: wrapOutputSchemaForLegacy(t.outputSchema) - } : t) - }; - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope: (_material) => void 0 -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/buildSchemas.ts -/** -* 2026-era wire schemas (protocol revision 2026-07-28). -* -* Fully self-contained — no runtime imports from types/schemas.ts. The -* neutral types/schemas.ts layer is the public-API superset and is free to -* evolve; this file is the 2026 wire-parse contract and is BEHAVIOR-FROZEN -* against the 2026-07-28 anchor. Every era-shared building block (content -* blocks, resources, prompts, capabilities, notifications, …) that the wire -* shapes compose is a frozen LOCAL copy — verbatim from the neutral layer at -* the point this revision was sealed, dependencies first. The only cross-layer -* dependency is `import type { JSONObject, JSONValue }` from the neutral types -* barrel — pure structural type aliases with no parse behavior. -* -* This module is the only place the per-request `_meta` envelope is modeled. -* The envelope is wire-only vocabulary: the protocol layer lifts it off -* inbound requests before any handler runs and surfaces it at -* `ctx.mcpReq.envelope`; the 2026-era codec enforces its requiredness at -* dispatch time (`checkInboundEnvelope`) - the former neutral-schema JSDoc -* deferral ("enforced per request at dispatch time, not here") is now -* discharged by that codec step. -* -* No 2025-era traffic ever touches this module, so requiredness here is -* bare and spec-exact (the shared-schema `.catch` hazards do not apply). -* -* SPEC-CURRENCY RE-SEAL (2026-07-17): the 2026-07-28 revision was re-sealed -* upstream by spec PR #3002 (commit 71e30695, merged 2026-07-15 — after the -* previous anchor pin f68d864a): the envelope's `clientInfo` demoted from -* required to SHOULD, and `DiscoverResult.serverInfo` moved from the result -* body to the new `ResultMetaObject` key -* `_meta['io.modelcontextprotocol/serverInfo']` (optional on every result). -* The shapes below are the re-sealed anchor, exactly — no pre-#3002 shape is -* modeled anywhere (per ruling: the final revision is the only 2026-07-28). -*/ -function build() { - const JSONValueSchema$1 = lazy(() => schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_null(), - schemas_record(schemas_string(), JSONValueSchema$1), - schemas_array(JSONValueSchema$1) - ])); - const JSONObjectSchema$1 = schemas_record(schemas_string(), JSONValueSchema$1); - /** - * A progress token, used to associate progress notifications with the original request. - */ - const ProgressTokenSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * An opaque token used to represent a cursor for pagination. - */ - const CursorSchema$1 = schemas_string(); - /** - * A uniquely identifying ID for a request in JSON-RPC. - */ - const RequestIdSchema$1 = schemas_union([schemas_string(), schemas_number().int()]); - /** - * The sender or recipient of messages and data in a conversation. - */ - const RoleSchema$1 = schemas_enum(["user", "assistant"]); - /** - * The severity of a log message. - */ - const LoggingLevelSchema$1 = schemas_enum([ - "debug", - "info", - "notice", - "warning", - "error", - "critical", - "alert", - "emergency" - ]); - /** - * A Zod schema for validating Base64 strings that is more performant and - * robust for very large inputs than the default regex-based check. It avoids - * stack overflows by using the native `atob` function for validation. - */ - const Base64Schema = schemas_string().refine((val) => { - try { - atob(val); - return true; - } catch { - return false; - } - }, { message: "Invalid Base64 string" }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskMetadataSchema$1 = schemas_object({ ttl: schemas_number().optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const RelatedTaskMetadataSchema$1 = schemas_object({ taskId: schemas_string() }); - const RequestMetaSchema$1 = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - "io.modelcontextprotocol/related-task": RelatedTaskMetadataSchema$1.optional() - }); - const BaseRequestParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const TaskAugmentedRequestParamsSchema$1 = BaseRequestParamsSchema$1.extend({ task: TaskMetadataSchema$1.optional() }); - const NotificationsParamsSchema$1 = schemas_object({ _meta: RequestMetaSchema$1.optional() }); - const NotificationSchema$1 = schemas_object({ - method: schemas_string(), - params: NotificationsParamsSchema$1.loose().optional() - }); - const IconSchema$1 = schemas_object({ - src: schemas_string(), - mimeType: schemas_string().optional(), - sizes: schemas_array(schemas_string()).optional(), - theme: schemas_enum(["light", "dark"]).optional() - }); - const IconsSchema$1 = schemas_object({ icons: schemas_array(IconSchema$1).optional() }); - const BaseMetadataSchema$1 = schemas_object({ - name: schemas_string(), - title: schemas_string().optional() - }); - const ImplementationSchema$1 = BaseMetadataSchema$1.extend({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - version: schemas_string(), - websiteUrl: schemas_string().optional(), - description: schemas_string().optional() - }); - const FormElicitationCapabilitySchema = intersection(schemas_object({ applyDefaults: schemas_boolean().optional() }), JSONObjectSchema$1); - const ElicitationCapabilitySchema = preprocess((value) => { - if (value && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) return { form: {} }; - return value; - }, intersection(schemas_object({ - form: FormElicitationCapabilitySchema.optional(), - url: JSONObjectSchema$1.optional() - }), JSONObjectSchema$1.optional())); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ClientTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ - sampling: looseObject({ createMessage: JSONObjectSchema$1.optional() }).optional(), - elicitation: looseObject({ create: JSONObjectSchema$1.optional() }).optional() - }).optional() - }); - /** @deprecated 2025-11-25 wire vocabulary with no SDK runtime; kept importable for interoperability only. */ - const ServerTasksCapabilitySchema$1 = looseObject({ - list: JSONObjectSchema$1.optional(), - cancel: JSONObjectSchema$1.optional(), - requests: looseObject({ tools: looseObject({ call: JSONObjectSchema$1.optional() }).optional() }).optional() - }); - const ClientCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - sampling: schemas_object({ - context: JSONObjectSchema$1.optional(), - tools: JSONObjectSchema$1.optional() - }).optional(), - elicitation: ElicitationCapabilitySchema.optional(), - roots: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ClientTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ServerCapabilitiesSchema$1 = schemas_object({ - experimental: schemas_record(schemas_string(), JSONObjectSchema$1).optional(), - logging: JSONObjectSchema$1.optional(), - completions: JSONObjectSchema$1.optional(), - prompts: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - resources: schemas_object({ - subscribe: schemas_boolean().optional(), - listChanged: schemas_boolean().optional() - }).optional(), - tools: schemas_object({ listChanged: schemas_boolean().optional() }).optional(), - tasks: ServerTasksCapabilitySchema$1.optional(), - extensions: schemas_record(schemas_string(), JSONObjectSchema$1).optional() - }); - const ProgressSchema$1 = schemas_object({ - progress: schemas_number(), - total: schemas_optional(schemas_number()), - message: schemas_optional(schemas_string()) - }); - const ProgressNotificationParamsSchema$1 = schemas_object({ - ...NotificationsParamsSchema$1.shape, - ...ProgressSchema$1.shape, - progressToken: ProgressTokenSchema$1 - }); - const ProgressNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/progress"), - params: ProgressNotificationParamsSchema$1 - }); - const LoggingMessageNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ - level: LoggingLevelSchema$1, - logger: schemas_string().optional(), - data: unknown() - }); - const LoggingMessageNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/message"), - params: LoggingMessageNotificationParamsSchema$1 - }); - const ResourceContentsSchema$1 = schemas_object({ - uri: schemas_string(), - mimeType: schemas_optional(schemas_string()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const TextResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ text: schemas_string() }); - const BlobResourceContentsSchema$1 = ResourceContentsSchema$1.extend({ blob: Base64Schema }); - const AnnotationsSchema$1 = schemas_object({ - audience: schemas_array(RoleSchema$1).optional(), - priority: schemas_number().min(0).max(1).optional(), - lastModified: iso_datetime({ offset: true }).optional() - }); - const ResourceSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uri: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - size: schemas_optional(schemas_number()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceTemplateSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - uriTemplate: schemas_string(), - description: schemas_optional(schemas_string()), - mimeType: schemas_optional(schemas_string()), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_optional(looseObject({})) - }); - const ResourceListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ResourceUpdatedNotificationParamsSchema$1 = NotificationsParamsSchema$1.extend({ uri: schemas_string() }); - const ResourceUpdatedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/resources/updated"), - params: ResourceUpdatedNotificationParamsSchema$1 - }); - const PromptArgumentSchema$1 = schemas_object({ - name: schemas_string(), - description: schemas_optional(schemas_string()), - required: schemas_optional(schemas_boolean()) - }); - const PromptSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_optional(schemas_string()), - arguments: schemas_optional(schemas_array(PromptArgumentSchema$1)), - _meta: schemas_optional(looseObject({})) - }); - const PromptListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/prompts/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const TextContentSchema$1 = schemas_object({ - type: literal("text"), - text: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ImageContentSchema$1 = schemas_object({ - type: literal("image"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const AudioContentSchema$1 = schemas_object({ - type: literal("audio"), - data: Base64Schema, - mimeType: schemas_string(), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ToolUseContentSchema$1 = schemas_object({ - type: literal("tool_use"), - name: schemas_string(), - id: schemas_string(), - input: schemas_record(schemas_string(), unknown()), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const EmbeddedResourceSchema$1 = schemas_object({ - type: literal("resource"), - resource: schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1]), - annotations: AnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const ResourceLinkSchema$1 = ResourceSchema$1.extend({ type: literal("resource_link") }); - const ContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ResourceLinkSchema$1, - EmbeddedResourceSchema$1 - ]); - const PromptMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: ContentBlockSchema$1 - }); - const ToolAnnotationsSchema$1 = schemas_object({ - title: schemas_string().optional(), - readOnlyHint: schemas_boolean().optional(), - destructiveHint: schemas_boolean().optional(), - idempotentHint: schemas_boolean().optional(), - openWorldHint: schemas_boolean().optional() - }); - const ToolListChangedNotificationSchema$1 = NotificationSchema$1.extend({ - method: literal("notifications/tools/list_changed"), - params: NotificationsParamsSchema$1.optional() - }); - const ModelHintSchema$1 = schemas_object({ name: schemas_string().optional() }); - const ModelPreferencesSchema$1 = schemas_object({ - hints: schemas_array(ModelHintSchema$1).optional(), - costPriority: schemas_number().min(0).max(1).optional(), - speedPriority: schemas_number().min(0).max(1).optional(), - intelligencePriority: schemas_number().min(0).max(1).optional() - }); - const ToolChoiceSchema$1 = schemas_object({ mode: schemas_enum([ - "auto", - "required", - "none" - ]).optional() }); - const BooleanSchemaSchema$1 = schemas_object({ - type: literal("boolean"), - title: schemas_string().optional(), - description: schemas_string().optional(), - default: schemas_boolean().optional() - }); - const StringSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minLength: schemas_number().optional(), - maxLength: schemas_number().optional(), - format: schemas_enum([ - "email", - "uri", - "date", - "date-time" - ]).optional(), - default: schemas_string().optional() - }); - const NumberSchemaSchema$1 = schemas_object({ - type: schemas_enum(["number", "integer"]), - title: schemas_string().optional(), - description: schemas_string().optional(), - minimum: schemas_number().optional(), - maximum: schemas_number().optional(), - default: schemas_number().optional() - }); - const UntitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - default: schemas_string().optional() - }); - const TitledSingleSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - oneOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })), - default: schemas_string().optional() - }); - const LegacyTitledEnumSchemaSchema$1 = schemas_object({ - type: literal("string"), - title: schemas_string().optional(), - description: schemas_string().optional(), - enum: schemas_array(schemas_string()), - enumNames: schemas_array(schemas_string()).optional(), - default: schemas_string().optional() - }); - const SingleSelectEnumSchemaSchema$1 = schemas_union([UntitledSingleSelectEnumSchemaSchema$1, TitledSingleSelectEnumSchemaSchema$1]); - const UntitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ - type: literal("string"), - enum: schemas_array(schemas_string()) - }), - default: schemas_array(schemas_string()).optional() - }); - const TitledMultiSelectEnumSchemaSchema$1 = schemas_object({ - type: literal("array"), - title: schemas_string().optional(), - description: schemas_string().optional(), - minItems: schemas_number().optional(), - maxItems: schemas_number().optional(), - items: schemas_object({ anyOf: schemas_array(schemas_object({ - const: schemas_string(), - title: schemas_string() - })) }), - default: schemas_array(schemas_string()).optional() - }); - const MultiSelectEnumSchemaSchema$1 = schemas_union([UntitledMultiSelectEnumSchemaSchema$1, TitledMultiSelectEnumSchemaSchema$1]); - const EnumSchemaSchema$1 = schemas_union([ - LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema$1 - ]); - const PrimitiveSchemaDefinitionSchema$1 = schemas_union([ - EnumSchemaSchema$1, - BooleanSchemaSchema$1, - StringSchemaSchema$1, - NumberSchemaSchema$1 - ]); - const ElicitRequestFormParamsSchema$1 = TaskAugmentedRequestParamsSchema$1.extend({ - mode: literal("form").optional(), - message: schemas_string(), - requestedSchema: schemas_object({ - type: literal("object"), - properties: schemas_record(schemas_string(), PrimitiveSchemaDefinitionSchema$1), - required: schemas_array(schemas_string()).optional() - }).catchall(unknown()) - }); - const ResourceTemplateReferenceSchema$1 = schemas_object({ - type: literal("ref/resource"), - uri: schemas_string() - }); - const PromptReferenceSchema$1 = schemas_object({ - type: literal("ref/prompt"), - name: schemas_string() - }); - const RootSchema$1 = schemas_object({ - uri: schemas_string().startsWith("file://"), - name: schemas_string().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - const sharedClientCapabilityShape = ClientCapabilitiesSchema$1.shape; - const ClientCapabilities2026Schema = schemas_object({ - experimental: sharedClientCapabilityShape.experimental, - sampling: sharedClientCapabilityShape.sampling, - elicitation: sharedClientCapabilityShape.elicitation, - roots: sharedClientCapabilityShape.roots, - extensions: sharedClientCapabilityShape.extensions - }); - const sharedServerCapabilityShape = ServerCapabilitiesSchema$1.shape; - const ServerCapabilities2026Schema = schemas_object({ - experimental: sharedServerCapabilityShape.experimental, - logging: sharedServerCapabilityShape.logging, - completions: sharedServerCapabilityShape.completions, - prompts: sharedServerCapabilityShape.prompts, - resources: sharedServerCapabilityShape.resources, - tools: sharedServerCapabilityShape.tools, - extensions: sharedServerCapabilityShape.extensions - }); - /** - * The per-request `_meta` envelope carried by every request under protocol revision - * 2026-07-28: the protocol version governing the request, the client implementation - * info, and the client's capabilities — declared per request rather than once at - * initialization — plus the optional log-level opt-in. - * - * This schema models the complete envelope on its own (loose: foreign keys - * pass through - the lift extracts exactly the reserved keys, so enforcement - * never sees extension material). Requiredness is enforced per request at - * dispatch time by the 2026-era codec's `checkInboundEnvelope` step. - */ - const RequestMetaEnvelopeSchema = looseObject({ - progressToken: ProgressTokenSchema$1.optional(), - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: schemas_string(), - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: ImplementationSchema$1.optional(), - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: ClientCapabilities2026Schema, - [LOG_LEVEL_META_KEY]: LoggingLevelSchema$1.optional() - }); - /** 2026-era Tool: anchor-exact — no `execution` (deleted vocabulary). */ - const ToolSchema$1 = schemas_object({ - ...BaseMetadataSchema$1.shape, - ...IconsSchema$1.shape, - description: schemas_string().optional(), - inputSchema: looseObject({ - $schema: schemas_string().optional(), - type: literal("object") - }), - outputSchema: looseObject({ $schema: schemas_string().optional() }).optional(), - annotations: ToolAnnotationsSchema$1.optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era ToolResultContent (anchor-exact: `structuredContent?: unknown`). */ - const ToolResultContentSchema$1 = schemas_object({ - type: literal("tool_result"), - toolUseId: schemas_string(), - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional(), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** 2026-era sampling content union (composes the forked tool-result shape). */ - const SamplingMessageContentBlockSchema$1 = schemas_union([ - TextContentSchema$1, - ImageContentSchema$1, - AudioContentSchema$1, - ToolUseContentSchema$1, - ToolResultContentSchema$1 - ]); - /** 2026-era SamplingMessage (anchor-exact: single block or array). */ - const SamplingMessageSchema$1 = schemas_object({ - role: RoleSchema$1, - content: schemas_union([SamplingMessageContentBlockSchema$1, schemas_array(SamplingMessageContentBlockSchema$1)]), - _meta: schemas_record(schemas_string(), unknown()).optional() - }); - /** Open union per the anchor: 'complete' | 'input_required' | string. */ - const ResultTypeSchema = schemas_string(); - /** - * Result `_meta` (anchor `ResultMetaObject`, added by spec PR #3002): - * loose, with the serverInfo key typed when present; the outbound stamp - * is the encode contract's `stampServerInfoMeta` step. - */ - const ResultMetaSchema = looseObject({ [auth_CUe6YdwF_SERVER_INFO_META_KEY]: ImplementationSchema$1.optional().catch(void 0) }); - const wireMeta = ResultMetaSchema.optional(); - function wireResult(shape) { - return looseObject({ - _meta: wireMeta, - resultType: ResultTypeSchema.default("complete"), - ...shape - }); - } - const ResultSchema$1 = wireResult({}); - const PaginatedResultSchema$1 = wireResult({ nextCursor: CursorSchema$1.optional() }); - const CallToolResultSchema$1 = wireResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }); - const ListToolsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListPromptsResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const GetPromptResultSchema$1 = wireResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }); - const ListResourcesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ListResourceTemplatesResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }); - const ReadResourceResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }); - const CompleteResultSchema$1 = wireResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }); - /** CacheableResult (SEP-2549): ttlMs and cacheScope REQUIRED per the anchor. */ - const CacheableResultSchema = wireResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]) - }); - const DiscoverResultSchema$1 = wireResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }); - /** 2026-era CreateMessageRequestParams (anchor-exact: forked SamplingMessage/Tool, no task augmentation). */ - const CreateMessageRequestParamsSchema$1 = schemas_object({ - messages: schemas_array(SamplingMessageSchema$1), - modelPreferences: ModelPreferencesSchema$1.optional(), - systemPrompt: schemas_string().optional(), - includeContext: schemas_enum([ - "none", - "thisServer", - "allServers" - ]).optional(), - temperature: schemas_number().optional(), - maxTokens: schemas_number().int(), - stopSequences: schemas_array(schemas_string()).optional(), - metadata: JSONObjectSchema$1.optional(), - tools: schemas_array(ToolSchema$1).optional(), - toolChoice: ToolChoiceSchema$1.optional() - }); - /** 2026-era embedded sampling request (de-JSON-RPC'd). */ - const CreateMessageRequestSchema$1 = schemas_object({ - method: literal("sampling/createMessage"), - params: CreateMessageRequestParamsSchema$1 - }); - /** - * 2026-era embedded roots listing request (de-JSON-RPC'd). Embedded input - * requests do NOT carry the per-request `_meta` envelope on this revision — - * the anchor declares a bare optional `_meta` on `params`. - */ - const ListRootsRequestSchema$1 = schemas_object({ - method: literal("roots/list"), - params: schemas_object({ _meta: schemas_record(schemas_string(), unknown()).optional() }).optional() - }); - /** 2026-era embedded sampling response (anchor-exact: extends the forked SamplingMessage). */ - const CreateMessageResultSchema$1 = schemas_object({ - ...SamplingMessageSchema$1.shape, - model: schemas_string(), - stopReason: schemas_string().optional() - }); - /** 2026-era embedded roots listing response (anchor-exact: bare `roots` array). */ - const ListRootsResultSchema$1 = schemas_object({ roots: schemas_array(RootSchema$1) }); - /** 2026-era embedded elicitation response (anchor-exact: bare result, restricted content value types). */ - const ElicitResultSchema$1 = schemas_object({ - action: schemas_enum([ - "accept", - "decline", - "cancel" - ]), - content: schemas_record(schemas_string(), schemas_union([ - schemas_string(), - schemas_number(), - schemas_boolean(), - schemas_array(schemas_string()) - ])).optional() - }); - /** - * 2026-era URL-mode elicitation params (anchor-exact fork): the draft removed - * `elicitationId` (and the `notifications/elicitation/complete` channel it - * keyed) — the shared schema keeps the field because it is required on the - * frozen 2025-11-25 revision. - */ - const ElicitRequestURLParamsSchema$1 = schemas_object({ - mode: literal("url"), - message: schemas_string(), - url: schemas_string().url() - }); - /** 2026-era elicitation params (form mode is revision-identical; URL mode is the fork above). */ - const ElicitRequestParamsSchema$1 = schemas_union([ElicitRequestFormParamsSchema$1, ElicitRequestURLParamsSchema$1]); - /** 2026-era embedded elicitation request (de-JSON-RPC'd; see the URL-mode fork above). */ - const ElicitRequestSchema$1 = schemas_object({ - method: literal("elicitation/create"), - params: ElicitRequestParamsSchema$1 - }); - /** A single embedded input request (one of the three demoted server→client requests). */ - const InputRequestSchema = schemas_union([ - CreateMessageRequestSchema$1, - ListRootsRequestSchema$1, - ElicitRequestSchema$1 - ]); - /** A single embedded input response — the BARE result union (never a `{method, result}` wrapper). */ - const InputResponseSchema = schemas_union([ - CreateMessageResultSchema$1, - ListRootsResultSchema$1, - ElicitResultSchema$1 - ]); - /** Map of embedded input requests, keyed by server-assigned identifiers. */ - const InputRequestsSchema = schemas_record(schemas_string(), InputRequestSchema); - /** Map of embedded input responses, keyed by the corresponding request identifiers. */ - const InputResponsesSchema = schemas_record(schemas_string(), InputResponseSchema); - /** - * The wire InputRequiredResult: `resultType: 'input_required'` plus at least - * one of `inputRequests` / `requestState` (the at-least-one rule is enforced - * at the server seam, not by this parse shape). - */ - const InputRequiredResultSchema = wireResult({ - inputRequests: InputRequestsSchema.optional(), - requestState: schemas_string().optional() - }); - /** The retry-channel members carried by client-initiated requests on this revision. */ - const retryParamsShape = { - inputResponses: InputResponsesSchema.optional(), - requestState: schemas_string().optional() - }; - /** Anchor InputResponseRequestParams: the retry channel on top of the required request `_meta` envelope. */ - const InputResponseRequestParamsSchema = schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...retryParamsShape - }); - /** Post-lift request `_meta` (progressToken + extension keys; loose). */ - const DispatchRequestMetaSchema = looseObject({ progressToken: ProgressTokenSchema$1.optional() }); - function wireRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: RequestMetaEnvelopeSchema, - ...paramsShape - }) - }); - } - function dispatchRequest(method, paramsShape) { - return schemas_object({ - method: literal(method), - params: schemas_object({ - _meta: DispatchRequestMetaSchema.optional(), - ...paramsShape - }).optional() - }); - } - const callToolParamsShape = { - name: schemas_string(), - arguments: schemas_record(schemas_string(), unknown()).optional(), - ...retryParamsShape - }; - const paginatedParamsShape = { cursor: CursorSchema$1.optional() }; - const CallToolRequestSchema$1 = wireRequest("tools/call", callToolParamsShape); - const ListToolsRequestSchema$1 = wireRequest("tools/list", paginatedParamsShape); - const ListPromptsRequestSchema$1 = wireRequest("prompts/list", paginatedParamsShape); - const GetPromptRequestSchema$1 = wireRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional(), - ...retryParamsShape - }); - const ListResourcesRequestSchema$1 = wireRequest("resources/list", paginatedParamsShape); - const ListResourceTemplatesRequestSchema$1 = wireRequest("resources/templates/list", paginatedParamsShape); - const ReadResourceRequestSchema$1 = wireRequest("resources/read", { - uri: schemas_string(), - ...retryParamsShape - }); - const completeParamsShape = { - ref: schemas_union([PromptReferenceSchema$1, ResourceTemplateReferenceSchema$1]), - argument: schemas_object({ - name: schemas_string(), - value: schemas_string() - }), - context: schemas_object({ arguments: schemas_record(schemas_string(), schemas_string()).optional() }).optional() - }; - const CompleteRequestSchema$1 = wireRequest("completion/complete", completeParamsShape); - const DiscoverRequestSchema$1 = wireRequest("server/discover", {}); - /** Anchor SubscriptionFilter (2026-only). */ - const SubscriptionFilterSchema$1 = schemas_object({ - toolsListChanged: schemas_boolean().optional(), - promptsListChanged: schemas_boolean().optional(), - resourcesListChanged: schemas_boolean().optional(), - resourceSubscriptions: schemas_array(schemas_string()).optional() - }); - const subscriptionsListenParamsShape = { notifications: SubscriptionFilterSchema$1 }; - const SubscriptionsListenRequestSchema$1 = wireRequest("subscriptions/listen", subscriptionsListenParamsShape); - /** - * Anchor SubscriptionsListenResultMeta — required subscriptionId stamp on - * the graceful-close result. Extends `ResultMetaObject` since spec PR - * #3002 (composed, so the serverInfo key and its leniency stay single-sourced). - */ - const SubscriptionsListenResultMetaSchema$1 = ResultMetaSchema.extend({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1 }); - /** - * Anchor SubscriptionsListenResult (2026-only). The empty `subscriptions/listen` - * response signalling that the subscription has ended gracefully (server - * shutdown). An abrupt transport close carries no response — the client treats - * stream-close-without-result as a disconnect. - */ - const SubscriptionsListenResultSchema$1 = looseObject({ - _meta: SubscriptionsListenResultMetaSchema$1, - resultType: ResultTypeSchema.default("complete") - }); - /** Dispatch (post-lift) request schemas, keyed by method — registry-internal. */ - const dispatchRequestSchemas = { - "tools/call": dispatchRequest("tools/call", callToolParamsShape), - "tools/list": dispatchRequest("tools/list", paginatedParamsShape), - "prompts/get": dispatchRequest("prompts/get", { - name: schemas_string(), - arguments: schemas_record(schemas_string(), schemas_string()).optional() - }), - "prompts/list": dispatchRequest("prompts/list", paginatedParamsShape), - "resources/list": dispatchRequest("resources/list", paginatedParamsShape), - "resources/templates/list": dispatchRequest("resources/templates/list", paginatedParamsShape), - "resources/read": dispatchRequest("resources/read", { uri: schemas_string() }), - "completion/complete": dispatchRequest("completion/complete", completeParamsShape), - "server/discover": dispatchRequest("server/discover", {}), - "subscriptions/listen": dispatchRequest("subscriptions/listen", subscriptionsListenParamsShape) - }; - /** Dispatch (post-lift) result schemas, keyed by method — what the funnel - * validates AFTER `decodeResult` consumed `resultType`. */ - function liftedResult(shape) { - return looseObject({ - _meta: wireMeta, - ...shape - }); - } - const dispatchResultSchemas = { - "tools/call": liftedResult({ - content: schemas_array(ContentBlockSchema$1), - structuredContent: unknown().optional(), - isError: schemas_boolean().optional() - }), - "tools/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - tools: schemas_array(ToolSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "prompts/get": liftedResult({ - description: schemas_string().optional(), - messages: schemas_array(PromptMessageSchema$1) - }), - "prompts/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - prompts: schemas_array(PromptSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resources: schemas_array(ResourceSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/templates/list": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - resourceTemplates: schemas_array(ResourceTemplateSchema$1), - nextCursor: CursorSchema$1.optional() - }), - "resources/read": liftedResult({ - ttlMs: schemas_number().int().min(0), - cacheScope: schemas_enum(["public", "private"]), - contents: schemas_array(schemas_union([TextResourceContentsSchema$1, BlobResourceContentsSchema$1])) - }), - "completion/complete": liftedResult({ completion: schemas_object({ - values: schemas_array(schemas_string()).max(100), - total: schemas_number().int().optional(), - hasMore: schemas_boolean().optional() - }).loose() }), - "server/discover": liftedResult({ - ttlMs: schemas_number().int().min(0).catch(0), - cacheScope: schemas_enum(["public", "private"]).catch("private"), - supportedVersions: schemas_array(schemas_string()), - capabilities: ServerCapabilities2026Schema, - instructions: schemas_string().optional() - }), - "subscriptions/listen": liftedResult({}) - }; - /** - * Notification `_meta` (anchor `NotificationMetaObject`): loose, with the - * subscriptions/listen demux key typed when present. Only the anchor-exact - * SHAPE is modeled here — listen delivery itself (filter gating, demux, - * teardown) is #14 scope and not implemented by this module. - */ - const NotificationMetaSchema = looseObject({ "io.modelcontextprotocol/subscriptionId": RequestIdSchema$1.optional() }); - /** Anchor SubscriptionsAcknowledgedNotification (2026-only). */ - const SubscriptionsAcknowledgedNotificationSchema$1 = schemas_object({ - method: literal("notifications/subscriptions/acknowledged"), - params: schemas_object({ - _meta: NotificationMetaSchema.optional(), - notifications: SubscriptionFilterSchema$1 - }) - }); - /** - * 2026-era `notifications/cancelled` params (anchor-exact fork): `requestId` - * is REQUIRED on this revision — the shared schema keeps it optional because - * the frozen 2025-11-25 shape declares it optional (task cancellation goes - * through `tasks/cancel` there). Requiredness is bare because no 2025-era - * traffic touches this module. - */ - const CancelledNotificationParamsSchema$1 = schemas_object({ - _meta: NotificationMetaSchema.optional(), - requestId: RequestIdSchema$1, - reason: schemas_string().optional() - }); - /** 2026-era `notifications/cancelled` (see the params fork above). */ - const CancelledNotificationSchema$1 = schemas_object({ - method: literal("notifications/cancelled"), - params: CancelledNotificationParamsSchema$1 - }); - const notificationSchemas2026 = { - "notifications/cancelled": CancelledNotificationSchema$1, - "notifications/progress": ProgressNotificationSchema$1, - "notifications/message": LoggingMessageNotificationSchema$1, - "notifications/resources/updated": ResourceUpdatedNotificationSchema$1, - "notifications/resources/list_changed": ResourceListChangedNotificationSchema$1, - "notifications/tools/list_changed": ToolListChangedNotificationSchema$1, - "notifications/prompts/list_changed": PromptListChangedNotificationSchema$1, - "notifications/subscriptions/acknowledged": SubscriptionsAcknowledgedNotificationSchema$1 - }; - const wireResultResponse = (result) => schemas_object({ - jsonrpc: literal("2.0"), - id: schemas_union([schemas_string(), schemas_number().int()]), - result - }).strict(); - return { - JSONValueSchema: JSONValueSchema$1, - JSONObjectSchema: JSONObjectSchema$1, - ProgressTokenSchema: ProgressTokenSchema$1, - CursorSchema: CursorSchema$1, - RequestIdSchema: RequestIdSchema$1, - RoleSchema: RoleSchema$1, - LoggingLevelSchema: LoggingLevelSchema$1, - TaskMetadataSchema: TaskMetadataSchema$1, - RelatedTaskMetadataSchema: RelatedTaskMetadataSchema$1, - RequestMetaSchema: RequestMetaSchema$1, - BaseRequestParamsSchema: BaseRequestParamsSchema$1, - TaskAugmentedRequestParamsSchema: TaskAugmentedRequestParamsSchema$1, - NotificationsParamsSchema: NotificationsParamsSchema$1, - NotificationSchema: NotificationSchema$1, - IconSchema: IconSchema$1, - IconsSchema: IconsSchema$1, - BaseMetadataSchema: BaseMetadataSchema$1, - ImplementationSchema: ImplementationSchema$1, - ClientTasksCapabilitySchema: ClientTasksCapabilitySchema$1, - ServerTasksCapabilitySchema: ServerTasksCapabilitySchema$1, - ClientCapabilitiesSchema: ClientCapabilitiesSchema$1, - ServerCapabilitiesSchema: ServerCapabilitiesSchema$1, - ProgressSchema: ProgressSchema$1, - ProgressNotificationParamsSchema: ProgressNotificationParamsSchema$1, - ProgressNotificationSchema: ProgressNotificationSchema$1, - LoggingMessageNotificationParamsSchema: LoggingMessageNotificationParamsSchema$1, - LoggingMessageNotificationSchema: LoggingMessageNotificationSchema$1, - ResourceContentsSchema: ResourceContentsSchema$1, - TextResourceContentsSchema: TextResourceContentsSchema$1, - BlobResourceContentsSchema: BlobResourceContentsSchema$1, - AnnotationsSchema: AnnotationsSchema$1, - ResourceSchema: ResourceSchema$1, - ResourceTemplateSchema: ResourceTemplateSchema$1, - ResourceListChangedNotificationSchema: ResourceListChangedNotificationSchema$1, - ResourceUpdatedNotificationParamsSchema: ResourceUpdatedNotificationParamsSchema$1, - ResourceUpdatedNotificationSchema: ResourceUpdatedNotificationSchema$1, - PromptArgumentSchema: PromptArgumentSchema$1, - PromptSchema: PromptSchema$1, - PromptListChangedNotificationSchema: PromptListChangedNotificationSchema$1, - TextContentSchema: TextContentSchema$1, - ImageContentSchema: ImageContentSchema$1, - AudioContentSchema: AudioContentSchema$1, - ToolUseContentSchema: ToolUseContentSchema$1, - EmbeddedResourceSchema: EmbeddedResourceSchema$1, - ResourceLinkSchema: ResourceLinkSchema$1, - ContentBlockSchema: ContentBlockSchema$1, - PromptMessageSchema: PromptMessageSchema$1, - ToolAnnotationsSchema: ToolAnnotationsSchema$1, - ToolListChangedNotificationSchema: ToolListChangedNotificationSchema$1, - ModelHintSchema: ModelHintSchema$1, - ModelPreferencesSchema: ModelPreferencesSchema$1, - ToolChoiceSchema: ToolChoiceSchema$1, - BooleanSchemaSchema: BooleanSchemaSchema$1, - StringSchemaSchema: StringSchemaSchema$1, - NumberSchemaSchema: NumberSchemaSchema$1, - UntitledSingleSelectEnumSchemaSchema: UntitledSingleSelectEnumSchemaSchema$1, - TitledSingleSelectEnumSchemaSchema: TitledSingleSelectEnumSchemaSchema$1, - LegacyTitledEnumSchemaSchema: LegacyTitledEnumSchemaSchema$1, - SingleSelectEnumSchemaSchema: SingleSelectEnumSchemaSchema$1, - UntitledMultiSelectEnumSchemaSchema: UntitledMultiSelectEnumSchemaSchema$1, - TitledMultiSelectEnumSchemaSchema: TitledMultiSelectEnumSchemaSchema$1, - MultiSelectEnumSchemaSchema: MultiSelectEnumSchemaSchema$1, - EnumSchemaSchema: EnumSchemaSchema$1, - PrimitiveSchemaDefinitionSchema: PrimitiveSchemaDefinitionSchema$1, - ElicitRequestFormParamsSchema: ElicitRequestFormParamsSchema$1, - ResourceTemplateReferenceSchema: ResourceTemplateReferenceSchema$1, - PromptReferenceSchema: PromptReferenceSchema$1, - RootSchema: RootSchema$1, - ClientCapabilities2026Schema, - ServerCapabilities2026Schema, - RequestMetaEnvelopeSchema, - ToolSchema: ToolSchema$1, - ToolResultContentSchema: ToolResultContentSchema$1, - SamplingMessageContentBlockSchema: SamplingMessageContentBlockSchema$1, - SamplingMessageSchema: SamplingMessageSchema$1, - ResultTypeSchema, - ResultMetaSchema, - ResultSchema: ResultSchema$1, - PaginatedResultSchema: PaginatedResultSchema$1, - CallToolResultSchema: CallToolResultSchema$1, - ListToolsResultSchema: ListToolsResultSchema$1, - ListPromptsResultSchema: ListPromptsResultSchema$1, - GetPromptResultSchema: GetPromptResultSchema$1, - ListResourcesResultSchema: ListResourcesResultSchema$1, - ListResourceTemplatesResultSchema: ListResourceTemplatesResultSchema$1, - ReadResourceResultSchema: ReadResourceResultSchema$1, - CompleteResultSchema: CompleteResultSchema$1, - CacheableResultSchema, - DiscoverResultSchema: DiscoverResultSchema$1, - CreateMessageRequestParamsSchema: CreateMessageRequestParamsSchema$1, - CreateMessageRequestSchema: CreateMessageRequestSchema$1, - ListRootsRequestSchema: ListRootsRequestSchema$1, - CreateMessageResultSchema: CreateMessageResultSchema$1, - ListRootsResultSchema: ListRootsResultSchema$1, - ElicitResultSchema: ElicitResultSchema$1, - ElicitRequestURLParamsSchema: ElicitRequestURLParamsSchema$1, - ElicitRequestParamsSchema: ElicitRequestParamsSchema$1, - ElicitRequestSchema: ElicitRequestSchema$1, - InputRequestSchema, - InputResponseSchema, - InputRequestsSchema, - InputResponsesSchema, - InputRequiredResultSchema, - InputResponseRequestParamsSchema, - CallToolRequestSchema: CallToolRequestSchema$1, - ListToolsRequestSchema: ListToolsRequestSchema$1, - ListPromptsRequestSchema: ListPromptsRequestSchema$1, - GetPromptRequestSchema: GetPromptRequestSchema$1, - ListResourcesRequestSchema: ListResourcesRequestSchema$1, - ListResourceTemplatesRequestSchema: ListResourceTemplatesRequestSchema$1, - ReadResourceRequestSchema: ReadResourceRequestSchema$1, - CompleteRequestSchema: CompleteRequestSchema$1, - DiscoverRequestSchema: DiscoverRequestSchema$1, - SubscriptionFilterSchema: SubscriptionFilterSchema$1, - SubscriptionsListenRequestSchema: SubscriptionsListenRequestSchema$1, - SubscriptionsListenResultMetaSchema: SubscriptionsListenResultMetaSchema$1, - SubscriptionsListenResultSchema: SubscriptionsListenResultSchema$1, - dispatchRequestSchemas, - dispatchResultSchemas, - NotificationMetaSchema, - SubscriptionsAcknowledgedNotificationSchema: SubscriptionsAcknowledgedNotificationSchema$1, - CancelledNotificationParamsSchema: CancelledNotificationParamsSchema$1, - CancelledNotificationSchema: CancelledNotificationSchema$1, - notificationSchemas2026, - JSONRPCResultResponseSchema: wireResultResponse(ResultSchema$1), - CallToolResultResponseSchema: wireResultResponse(schemas_union([CallToolResultSchema$1, InputRequiredResultSchema])), - ListToolsResultResponseSchema: wireResultResponse(ListToolsResultSchema$1), - ListPromptsResultResponseSchema: wireResultResponse(ListPromptsResultSchema$1), - GetPromptResultResponseSchema: wireResultResponse(schemas_union([GetPromptResultSchema$1, InputRequiredResultSchema])), - ListResourcesResultResponseSchema: wireResultResponse(ListResourcesResultSchema$1), - ListResourceTemplatesResultResponseSchema: wireResultResponse(ListResourceTemplatesResultSchema$1), - ReadResourceResultResponseSchema: wireResultResponse(schemas_union([ReadResourceResultSchema$1, InputRequiredResultSchema])), - CompleteResultResponseSchema: wireResultResponse(CompleteResultSchema$1), - DiscoverResultResponseSchema: wireResultResponse(DiscoverResultSchema$1) - }; -} -let src_CX2iR2pK_memo; -/** -* Builds the era wire-schema set on first call and returns the same object -* thereafter. Module evaluation stays construction-free so importing the -* era codec/registry costs nothing until the first validation actually -* needs a schema; the registry, the codec, and the eager `schemas.ts` -* shim all pull through this memo, so reference identity holds across -* every consumer. -*/ -function buildSchemas2026() { - return src_CX2iR2pK_memo ??= build(); -} - -//#endregion -//#region ../core-internal/src/shared/resultCacheHints.ts -/** -* The operations whose results are cacheable on the 2026-07-28 revision (the -* `CacheableResult` extenders). This list is closed: no other operation's -* result ever receives cache fields from the SDK. -*/ -const CACHEABLE_RESULT_METHODS = [ - "tools/list", - "prompts/list", - "resources/list", - "resources/templates/list", - "resources/read", - "server/discover" -]; -/** Whether the given method's result is cacheable on the 2026-07-28 revision. */ -function isCacheableResultMethod(method) { - return CACHEABLE_RESULT_METHODS.includes(method); -} -/** -* The symbol-keyed carrier for a configured cache hint on a result object. -* Symbol properties are invisible to JSON serialization, so the carrier can be -* attached era-blind: only the 2026-era encode seam consumes it. -*/ -const RESULT_CACHE_HINT_FALLBACK = Symbol("modelcontextprotocol.resultCacheHintFallback"); -/** -* Attaches a configured cache hint to a result as the encode-time fallback. -* Returns the result unchanged when there is nothing to attach. When a more -* specific hint is already attached, the two hints are combined per field -* (most-specific-author-wins for each of `ttlMs` and `cacheScope`): the -* per-registration hint attached by the feature layer keeps every field it -* sets, and the server-level per-operation hint only fills the fields the -* more specific hint leaves unset. -*/ -function attachCacheHintFallback(result, hint) { - if (hint === void 0) return result; - const attached = result[RESULT_CACHE_HINT_FALLBACK]; - if (attached === void 0) return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: hint - }; - const merged = {}; - const ttlMs = attached.ttlMs ?? hint.ttlMs; - if (ttlMs !== void 0) merged.ttlMs = ttlMs; - const cacheScope = attached.cacheScope ?? hint.cacheScope; - if (cacheScope !== void 0) merged.cacheScope = cacheScope; - return { - ...result, - [RESULT_CACHE_HINT_FALLBACK]: merged - }; -} -/** Reads the configured cache-hint fallback attached to a result, if any. */ -function cacheHintFallbackOf(result) { - return result[RESULT_CACHE_HINT_FALLBACK]; -} -/** -* Whether a value is a valid `ttlMs`: a non-negative safe integer. Safe -* integers are required because the wire schemas validate `ttlMs` as an -* integer within `Number.MIN_SAFE_INTEGER`/`Number.MAX_SAFE_INTEGER`; a value -* outside that range is treated as invalid here so it falls through to the -* next author instead of being emitted and rejected downstream. -*/ -function isValidCacheTtlMs(value) { - return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; -} -/** Whether a value is a valid `cacheScope`. */ -function isValidCacheScope(value) { - return value === "public" || value === "private"; -} -/** -* Validates a configured cache hint at configuration time. Throws a -* `RangeError` naming the offending field, so misconfiguration fails at -* startup/registration rather than silently degrading at encode time. -*/ -function assertValidCacheHint(hint, context) { - if (hint.ttlMs !== void 0 && !isValidCacheTtlMs(hint.ttlMs)) throw new RangeError(`Invalid cache hint for ${context}: ttlMs must be a non-negative safe integer (got ${String(hint.ttlMs)})`); - if (hint.cacheScope !== void 0 && !isValidCacheScope(hint.cacheScope)) throw new RangeError(`Invalid cache hint for ${context}: cacheScope must be 'public' or 'private' (got ${String(hint.cacheScope)})`); -} - -//#endregion -//#region ../core-internal/src/types/enums.ts -/** -* Error codes for protocol errors that cross the wire as JSON-RPC error responses. -* These follow the JSON-RPC specification and MCP-specific extensions. -*/ -let src_CX2iR2pK_ProtocolErrorCode = /* @__PURE__ */ function(ProtocolErrorCode$1) { - ProtocolErrorCode$1[ProtocolErrorCode$1["ParseError"] = -32700] = "ParseError"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidRequest"] = -32600] = "InvalidRequest"; - ProtocolErrorCode$1[ProtocolErrorCode$1["MethodNotFound"] = -32601] = "MethodNotFound"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InvalidParams"] = -32602] = "InvalidParams"; - ProtocolErrorCode$1[ProtocolErrorCode$1["InternalError"] = -32603] = "InternalError"; - /** - * Resource not found. - * - * Receive-tolerated only: the SDK never EMITS `-32002` — `resources/read` - * misses answer `-32602` (Invalid Params) on every protocol revision per - * the 2026-07-28 spec MUST, and a handler-thrown `-32002` is mapped to - * `-32602` at the era encode seam. The member stays importable so clients - * can recognise `-32002` from peers built on earlier SDK releases (the - * spec's "clients SHOULD also accept `-32002`" backwards-compatibility - * clause). Throw `ResourceNotFoundError` instead. - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["ResourceNotFound"] = -32002] = "ResourceNotFound"; - /** - * Processing the request requires a capability the client did not declare - * in the request's `clientCapabilities` (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["MissingRequiredClientCapability"] = -32021] = "MissingRequiredClientCapability"; - /** - * The request's protocol version is unknown to the server or unsupported - * by it (protocol revision 2026-07-28). - */ - ProtocolErrorCode$1[ProtocolErrorCode$1["UnsupportedProtocolVersion"] = -32022] = "UnsupportedProtocolVersion"; - ProtocolErrorCode$1[ProtocolErrorCode$1["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired"; - return ProtocolErrorCode$1; -}({}); - -//#endregion -//#region ../core-internal/src/types/errors.ts -/** -* Protocol errors are JSON-RPC errors that cross the wire as error responses. -* They use numeric error codes from the {@linkcode ProtocolErrorCode} enum. -* -* `instanceof` on this class (and its subclasses) is brand-matched, so it works -* across separately bundled copies of the SDK — e.g. an error constructed by -* `@modelcontextprotocol/client` matches the class re-exported by -* `@modelcontextprotocol/server` in the same process. -*/ -var src_CX2iR2pK_ProtocolError = class ProtocolError extends Error { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ProtocolError" }); - } - static [Symbol.hasInstance](value) { - return brandedHasInstance(this, value); - } - /** - * Brand-based type guard: equivalent to `value instanceof this`, as an - * explicit static predicate (the axios/AWS-SDK `isInstance` style). Reads - * the caller's own brand via `this`, so every branded subclass gets a - * correctly-scoped guard by inheritance. Must be invoked on the class — - * in callback position write `v => SdkError.isInstance(v)`, not - * `.filter(SdkError.isInstance)` (detached calls throw rather than - * silently matching nothing). - */ - static isInstance(value) { - if (typeof this !== "function") throw new TypeError("isInstance must be called on the class (e.g. `SdkError.isInstance(value)`); for callbacks use `v => SdkError.isInstance(v)`"); - return brandedHasInstance(this, value); - } - constructor(code, message, data) { - super(message); - this.code = code; - this.data = data; - this.name = "ProtocolError"; - stampErrorBrands(this, new.target); - } - /** - * Factory method to create the appropriate error type based on the error code and data - */ - static fromError(code, message, data) { - if (code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired && data) { - const errorData = data; - if (errorData.elicitations) return new UrlElicitationRequiredError(errorData.elicitations, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion && data) { - const errorData = data; - if (Array.isArray(errorData.supported) && typeof errorData.requested === "string") return new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: errorData.supported, - requested: errorData.requested - }, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.InvalidParams || code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound) { - const errorData = data; - if (typeof errorData?.uri === "string" && (code === src_CX2iR2pK_ProtocolErrorCode.ResourceNotFound || Object.keys(errorData).length === 1)) return new ResourceNotFoundError(errorData.uri, message); - } - if (code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability && data) { - const errorData = data; - if (errorData.requiredCapabilities !== null && typeof errorData.requiredCapabilities === "object" && !Array.isArray(errorData.requiredCapabilities)) return new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: errorData.requiredCapabilities }, message); - } - return new ProtocolError(code, message, data); - } -}; -/** -* Error type for a `resources/read` miss: the requested resource does not -* exist. The wire code is `-32602` (Invalid Params) on every protocol -* revision — the spec MUST for revision 2026-07-28, and the value the v1.x -* SDK has always emitted on earlier revisions. The error data echoes the -* requested URI. -* -* Recognise this error by checking `error.data` is exactly `{ uri: string }` -* (a `-32602` whose data carries `uri` and nothing else is resource-not-found; -* any other `-32602` is an ordinary Invalid Params). For backwards compatibility, clients should also -* accept `-32002` as resource not found — earlier SDK builds emitted that -* code, and {@linkcode ProtocolError.fromError} reconstructs this class for -* either code **when `error.data` carries `uri`** (a bare `-32002` without -* `data.uri` stays a generic {@linkcode ProtocolError}). `instanceof` checks -* are brand-matched and work across separately bundled copies of the SDK. -*/ -var ResourceNotFoundError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.ResourceNotFoundError" }); - } - constructor(uri, message = `Resource not found: ${uri}`) { - super(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, message, { uri }); - } - /** The URI that was requested and not found. */ - get uri() { - return this.data.uri; - } -}; -/** -* Specialized error type when a tool requires a URL mode elicitation. -* This makes it nicer for the client to handle since there is specific data to work with instead of just a code to check against. -*/ -var UrlElicitationRequiredError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UrlElicitationRequiredError" }); - } - constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) { - super(src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired, message, { elicitations }); - } - get elicitations() { - return this.data?.elicitations ?? []; - } -}; -/** -* Error type for the `-32022` UnsupportedProtocolVersion protocol error (protocol -* revision 2026-07-28): the request's protocol version is unknown to the server or -* unsupported by it. -* -* The error data lists the protocol versions the receiver supports (`supported`), -* so the sender can choose a mutually supported version and retry, and echoes the -* version that was requested (`requested`). -*/ -var src_CX2iR2pK_UnsupportedProtocolVersionError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.UnsupportedProtocolVersionError" }); - } - constructor(data, message = `Unsupported protocol version: ${data.requested}`) { - super(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, message, data); - } - /** - * Protocol versions the receiver supports. - */ - get supported() { - return this.data.supported; - } - /** - * The protocol version that was requested. - */ - get requested() { - return this.data.requested; - } -}; -/** -* Error type for the `-32021` MissingRequiredClientCapability protocol error -* (protocol revision 2026-07-28): processing the request requires a capability -* the client did not declare in the request's `clientCapabilities`. -* -* The error data lists the missing capabilities (`requiredCapabilities`) in -* the `ClientCapabilities` shape, so the client can see exactly what it would -* have to declare for the request to be served. On HTTP, the response status -* is `400 Bad Request`. -* -* Recognize this error by its code and `data.requiredCapabilities`, or by -* `instanceof` — checks are brand-matched and work across separately bundled -* copies of the SDK. -*/ -var src_CX2iR2pK_MissingRequiredClientCapabilityError = class extends src_CX2iR2pK_ProtocolError { - static { - Object.defineProperty(this, "mcpBrand", { value: "mcp.MissingRequiredClientCapabilityError" }); - } - constructor(data, message = `Missing required client capabilities: ${Object.keys(data.requiredCapabilities).join(", ")}`) { - super(src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability, message, data); - } - /** - * The capabilities the server requires from the client to process the - * request (only the missing capabilities are listed). - */ - get requiredCapabilities() { - return this.data.requiredCapabilities; - } -}; - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/encodeContract.ts -/** The default cache policy when neither the handler nor configuration provides one. */ -const DEFAULT_CACHE_TTL_MS = 0; -const DEFAULT_CACHE_SCOPE = "private"; -/** -* Request methods whose spec result vocabulary goes beyond `'complete'` on the -* 2026-07-28 revision: their results may be `input_required` (multi -* round-trip requests), so a handler-provided `resultType` passes through the -* stamp untouched. `subscriptions/listen` is NOT in this set: it never emits -* a JSON-RPC result — termination is stream close (HTTP) or -* `notifications/cancelled` (stdio) per the spec. -*/ -const EXTENDED_RESULT_TYPE_METHODS = [ - "tools/call", - "prompts/get", - "resources/read" -]; -/** -* Step 1 of the encode contract: ensure the outbound result carries the -* required `resultType` discriminator. -* -* - No handler-provided value → stamp `'complete'`. -* - Handler-provided `'complete'` → kept as-is. -* - Handler-provided non-`'complete'` value on a method whose vocabulary -* allows it ({@linkcode EXTENDED_RESULT_TYPE_METHODS}) → passes through. -* The value is forwarded verbatim — the wire vocabulary is an open union and -* the SDK does not validate the string, so emitting a `resultType` the -* negotiated revision does not define is the handler author's -* responsibility. -* - Handler-provided non-`'complete'` value on any other method → internal -* error (loud): the value would be mis-typed on the wire, and silently -* rewriting it would hide a server bug. -*/ -function stampResultType(method, result) { - const provided = result["resultType"]; - if (provided === void 0) return { - ...result, - resultType: "complete" - }; - if (provided === "complete") return result; - if (EXTENDED_RESULT_TYPE_METHODS.includes(method)) return result; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned resultType '${String(provided)}', but results of ${method} only support 'complete' on protocol revision 2026-07-28`); -} -/** -* Step 2 of the encode contract: fill the required `ttlMs`/`cacheScope` fields -* on cacheable results. -* -* Applies only when the (post-stamp) `resultType` is `'complete'` and the -* method is one of the cacheable operations; everything else is returned -* untouched apart from removing the configured-hint carrier. Field resolution -* is per field, most specific author first: a valid handler-returned value, -* then the configured cache hint attached by the server layer, then the -* defaults. Handler-returned values are validated at encode time (`ttlMs` -* must be a non-negative integer, `cacheScope` must be `'public'` or -* `'private'`); invalid values are ignored rather than emitted. -*/ -function fillCacheFields(method, result) { - const fallback = cacheHintFallbackOf(result); - if (result["resultType"] !== "complete" || !isCacheableResultMethod(method)) return fallback === void 0 ? result : stripCacheHintFallback(result); - const provided = result; - const ttlMs = isValidCacheTtlMs(provided["ttlMs"]) ? provided["ttlMs"] : resolveTtlMs(fallback); - const cacheScope = isValidCacheScope(provided["cacheScope"]) ? provided["cacheScope"] : resolveCacheScope(fallback); - const filled = { - ...provided, - ttlMs, - cacheScope - }; - delete filled[RESULT_CACHE_HINT_FALLBACK]; - return filled; -} -function isPlainObject$5(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** -* Step 3 of the encode contract: stamp the server's identity into the -* result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR #3002: -* servers SHOULD include it on every response). -* -* - No `serverInfo` supplied (a client instance, or a hand-constructed -* protocol object) → identity function. -* - The result's `_meta` already carries the key → kept as-is (the handler -* is the more specific author; mirrors the cache-fill resolution order). -* - A present-but-non-object `_meta` (a dynamic-caller bug) → kept as-is: -* the stamp never rewrites handler material, and the malformed value fails -* loudly at the peer instead of being silently replaced here. -* - Otherwise → the key is added, preserving any other `_meta` entries. -* -* Runs for every result regardless of `resultType`: the anchor types -* `Result._meta` as `ResultMetaObject` on all results, `input_required` -* included. -*/ -function stampServerInfoMeta(result, serverInfo) { - if (serverInfo === void 0) return result; - const meta = result["_meta"]; - if (meta === void 0) return { - ...result, - _meta: { [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo } - }; - if (!isPlainObject$5(meta)) return result; - if (meta[auth_CUe6YdwF_SERVER_INFO_META_KEY] !== void 0) return result; - return { - ...result, - _meta: { - ...meta, - [auth_CUe6YdwF_SERVER_INFO_META_KEY]: serverInfo - } - }; -} -function resolveTtlMs(fallback) { - return fallback !== void 0 && isValidCacheTtlMs(fallback.ttlMs) ? fallback.ttlMs : DEFAULT_CACHE_TTL_MS; -} -function resolveCacheScope(fallback) { - return fallback !== void 0 && isValidCacheScope(fallback.cacheScope) ? fallback.cacheScope : DEFAULT_CACHE_SCOPE; -} -function stripCacheHintFallback(result) { - const copy = { ...result }; - delete copy[RESULT_CACHE_HINT_FALLBACK]; - return copy; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/inputRequired.ts -/** -* In-band input-request vocabulary of the 2026-07-28 revision (SEP-2322 -* multi round-trip requests), dispatch view. -* -* The three former server→client wire requests (`elicitation/create`, -* `sampling/createMessage`, `roots/list`) are NOT wire request methods on -* this revision — they are demoted to de-JSON-RPC'd payloads embedded in an -* `input_required` result. The multi-round-trip driver dispatches those -* embedded payloads to the client's registered handlers through the normal -* handler machinery, and these are the schemas that dispatch parses them -* with: lenient where the anchor's wire-true artifacts are strict (an -* embedded request never carries the per-request `_meta` envelope), exact -* where the vocabulary forks (the sampling shapes compose the forked -* SamplingMessage/Tool payloads). -* -* Registry membership is intentionally NOT granted here — these methods stay -* absent from the 2026-era request registry (a peer sending one as a wire -* request still gets −32601 by absence). Only the codec's -* `inputRequestSchema`/`inputResponseSchema` accessors expose them. -*/ -/** The embedded input-request methods of the 2026-07-28 revision. */ -const INPUT_REQUEST_METHODS_2026 = [ - "elicitation/create", - "sampling/createMessage", - "roots/list" -]; -let maps; -function inputSchemaMaps() { - if (maps) return maps; - const s = buildSchemas2026(); - maps = { - request: { - "elicitation/create": schemas_object({ - method: literal("elicitation/create"), - params: s.ElicitRequestParamsSchema - }), - "sampling/createMessage": schemas_object({ - method: literal("sampling/createMessage"), - params: s.CreateMessageRequestParamsSchema - }), - "roots/list": schemas_object({ - method: literal("roots/list"), - params: looseObject({}).optional() - }) - }, - response: { - "elicitation/create": s.ElicitResultSchema, - "sampling/createMessage": s.CreateMessageResultSchema, - "roots/list": s.ListRootsResultSchema - } - }; - return maps; -} -/** -* Forces the lazy embedded-request maps (and, through them, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the maps exist. -*/ -function warmInputSchemaMaps2026() { - inputSchemaMaps(); -} -function isInputRequestMethod2026(method) { - return INPUT_REQUEST_METHODS_2026.includes(method); -} -function getInputRequestSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().request[method] : void 0; -} -function getInputResponseSchema2026(method) { - return isInputRequestMethod2026(method) ? inputSchemaMaps().response[method] : void 0; -} - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/registry.ts -const requestMethodKeys = { - "tools/call": null, - "tools/list": null, - "prompts/get": null, - "prompts/list": null, - "resources/list": null, - "resources/templates/list": null, - "resources/read": null, - "completion/complete": null, - "server/discover": null, - "subscriptions/listen": null -}; -const notificationMethodKeys = { - "notifications/cancelled": null, - "notifications/progress": null, - "notifications/message": null, - "notifications/resources/updated": null, - "notifications/resources/list_changed": null, - "notifications/tools/list_changed": null, - "notifications/prompts/list_changed": null, - "notifications/subscriptions/acknowledged": null -}; -/** The 2026-era request-method set (registry membership = the deletion story). */ -function hasRequestMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -/** The 2026-era notification-method set. */ -function hasNotificationMethod2026(method) { - return Object.prototype.hasOwnProperty.call(notificationMethodKeys, method); -} -/** Result-map membership (same key set as the request map on this era). */ -function hasResultMethod2026(method) { - return Object.prototype.hasOwnProperty.call(requestMethodKeys, method); -} -function getRequestSchema2026(method) { - return hasRequestMethod2026(method) ? buildSchemas2026().dispatchRequestSchemas[method] : void 0; -} -function getResultSchema2026(method) { - return hasResultMethod2026(method) ? buildSchemas2026().dispatchResultSchemas[method] : void 0; -} -function getNotificationSchema2026(method) { - return hasNotificationMethod2026(method) ? buildSchemas2026().notificationSchemas2026[method] : void 0; -} -/** Registry method lists (for the spec-method universe and the CI registry-diff oracle). */ -const rev2026RequestMethods = Object.keys(requestMethodKeys); -const rev2026NotificationMethods = Object.keys(notificationMethodKeys); - -//#endregion -//#region ../core-internal/src/wire/rev2026-07-28/codec.ts -function isPlainObject$4(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** Tri-state wrap of an optional Zod schema lookup (the function-only contract). */ -function triState(schema, raw) { - if (schema === void 0) return { - ok: false, - reason: "not-in-era" - }; - const parsed = schema.safeParse(raw); - return parsed.success ? { - ok: true, - value: parsed.data - } : { - ok: false, - reason: "invalid", - message: String(parsed.error) - }; -} -const NOT_IN_ERA = { - ok: false, - reason: "not-in-era" -}; -/** -* The reserved `_meta` keys an envelope must carry on this era (in reporting -* order). `clientInfo` is NOT here: spec PR #3002 demoted it to SHOULD, so a -* request without it is accepted (a present-but-malformed value still fails -* the envelope schema parse below). -*/ -const REQUIRED_ENVELOPE_KEYS = [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]; -/** Strip the known deleted-field set from an outbound result (Q1-SD3 iii). */ -function enforceDeletedFields(method, result) { - let next = result; - let copied = false; - const copy = () => { - if (!copied) { - next = { ...next }; - copied = true; - } - return next; - }; - const tools = result.tools; - if (method === "tools/list" && Array.isArray(tools) && tools.some((tool) => isPlainObject$4(tool) && "execution" in tool)) copy().tools = tools.map((tool) => { - if (!isPlainObject$4(tool) || !("execution" in tool)) return tool; - const rest = { ...tool }; - delete rest["execution"]; - return rest; - }); - const capabilities = result.capabilities; - if (isPlainObject$4(capabilities) && "tasks" in capabilities) { - const rest = { ...capabilities }; - delete rest["tasks"]; - copy().capabilities = rest; - } - return next; -} -const rev2026Codec = { - era: "2026-07-28", - hasRequestMethod: hasRequestMethod2026, - hasNotificationMethod: hasNotificationMethod2026, - hasInputRequestMethod: (method) => getInputRequestSchema2026(method) !== void 0, - validateRequest: (method, raw) => triState(getRequestSchema2026(method), raw), - validateResult: (method, raw) => triState(getResultSchema2026(method), raw), - validateNotification: (method, raw) => triState(getNotificationSchema2026(method), raw), - validateInputRequest: (method, raw) => triState(getInputRequestSchema2026(method), raw), - validateInputResponse: (method, raw) => triState(getInputResponseSchema2026(method), raw), - samplingResultVariant: () => NOT_IN_ERA, - outboundEnvelope(material) { - return { - [auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY]: material.protocolVersion, - [auth_CUe6YdwF_CLIENT_INFO_META_KEY]: material.clientInfo, - [auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY]: material.clientCapabilities, - ...material.logLevel !== void 0 && { [LOG_LEVEL_META_KEY]: material.logLevel } - }; - }, - validateEnvelopeMeta(meta) { - const issues = []; - for (const key of REQUIRED_ENVELOPE_KEYS) if (!(key in meta)) issues.push({ - key, - problem: "missing" - }); - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(meta); - if (!parsed.success) for (const issue of parsed.error.issues) { - const path = issue.path.map(String); - const key = path.length > 0 ? path.join(".") : "_meta"; - if (path.length === 1 && issues.some((existing) => existing.key === key && existing.problem === "missing")) continue; - issues.push({ - key, - problem: issue.message - }); - } - return issues; - }, - projectCallToolResult: (result) => appendTextFallbackForNonObject(result), - inputRequestSchema: getInputRequestSchema2026, - decodeResult(method, raw) { - if (!isPlainObject$4(raw)) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: not an object`, { method }) - }; - const rawResultType = raw["resultType"]; - if (rawResultType === void 0) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: missing required resultType — servers implementing protocol revision 2026-07-28 MUST include it (the absent-means-complete bridge applies only to earlier-revision servers)`, { - method, - violation: "missing-resultType" - }) - }; - if (typeof rawResultType !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: non-string resultType`, { - method, - resultType: rawResultType - }) - }; - if (rawResultType === "input_required") { - const rawInputRequests = raw["inputRequests"]; - const inputRequests = isPlainObject$4(rawInputRequests) ? rawInputRequests : {}; - const requestState = raw["requestState"]; - if (Object.keys(inputRequests).length === 0 && typeof requestState !== "string") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: input_required carries neither inputRequests nor requestState (every input_required result must include at least one of the two)`, { - method, - violation: "input-required-missing-both" - }) - }; - return { - kind: "input_required", - inputRequests, - ...typeof requestState === "string" && { requestState } - }; - } - if (rawResultType !== "complete") return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${rawResultType}' for ${method}`, { - resultType: rawResultType, - method - }) - }; - const wireResultSchemas = getWireResultSchemas(); - const wireSchema = Object.hasOwn(wireResultSchemas, method) ? wireResultSchemas[method] : void 0; - if (wireSchema !== void 0) { - const parsed = wireSchema.safeParse(raw); - if (!parsed.success) return { - kind: "invalid", - error: new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${method}: ${parsed.error}`, { method }) - }; - } - const lifted = { ...raw }; - delete lifted["resultType"]; - return { - kind: "complete", - result: lifted - }; - }, - encodeResult(method, result, serverInfo) { - return stampServerInfoMeta(fillCacheFields(method, stampResultType(method, enforceDeletedFields(method, result))), serverInfo); - }, - encodeErrorCode: (code) => code === -32002 ? -32602 : code, - checkInboundEnvelope(material) { - if (material.envelope === void 0) return "Request is missing the required _meta envelope for protocol revision 2026-07-28 (io.modelcontextprotocol/protocolVersion, io.modelcontextprotocol/clientCapabilities)"; - const parsed = buildSchemas2026().RequestMetaEnvelopeSchema.safeParse(material.envelope); - if (!parsed.success) return `Invalid _meta envelope for protocol revision 2026-07-28: ${parsed.error.issues.map((issue) => issue.message).join("; ")}`; - } -}; -/** Wire-true result wrappers consulted by decode step 2, keyed by method — -* built once through the era's schema memo on the first decode. */ -let wireResultSchemasMemo; -function getWireResultSchemas() { - if (wireResultSchemasMemo) return wireResultSchemasMemo; - const s = buildSchemas2026(); - wireResultSchemasMemo = { - "tools/call": s.CallToolResultSchema, - "tools/list": s.ListToolsResultSchema, - "prompts/get": s.GetPromptResultSchema, - "prompts/list": s.ListPromptsResultSchema, - "resources/list": s.ListResourcesResultSchema, - "resources/templates/list": s.ListResourceTemplatesResultSchema, - "resources/read": s.ReadResourceResultSchema, - "completion/complete": s.CompleteResultSchema, - "server/discover": s.DiscoverResultSchema - }; - return wireResultSchemasMemo; -} -/** -* Forces the lazy wire-result wrapper map (and, through it, the era's schema -* memo). Warm-up hook for `preloadSchemas()` — no-op once the map exists. -*/ -function warmWireResultSchemas2026() { - getWireResultSchemas(); -} - -//#endregion -//#region ../core-internal/src/wire/codec.ts -/** -* The modern wire revision literal. Internal only — deliberately NOT a public -* constant (G-D2-4: no public modern-version constant ships before era-aware -* list semantics exist). -*/ -const src_CX2iR2pK_MODERN_WIRE_REVISION = "2026-07-28"; -/** -* Era resolution, many-to-one (Q1-SD1): every modern-era revision -* (`>= 2026-07-28`) → the 2026-era codec; every legacy revision (the five -* `SUPPORTED_PROTOCOL_VERSIONS`) and `undefined`/unknown → the 2025-era -* codec (the DV-13 default posture — hand-constructed instances and -* unclassified traffic are legacy-era). This is the same era predicate the -* rest of the SDK uses ({@link isModernProtocolVersion}); a pinned modern -* revision other than the literal '2026-07-28' must still resolve modern. -*/ -function src_CX2iR2pK_codecForVersion(version) { - return version !== void 0 && isModernProtocolVersion(version) ? rev2026Codec : rev2025Codec; -} -/** -* The wire era an edge classification names (Q2 — produced at the -* transport/entry edge; this layer only CONSUMES it). The dispatch funnel no -* longer resolves a codec FROM the classification: era is instance state, and -* a classified inbound message is VALIDATED against the instance era — a -* mismatch is an entry/routing error, never a per-message era switch. The -* exact `revision` wins over the coarse era flag when both are present. -*/ -function classifiedWireEra(classification) { - if (classification.revision !== void 0) return src_CX2iR2pK_codecForVersion(classification.revision).era; - return classification.era === "modern" ? rev2026Codec.era : rev2025Codec.era; -} -/** -* The derived spec-method universe: the union of every codec registry. A -* method in this set is era-gated at dispatch and send time; a method outside -* it is a consumer-owned extension method (era-blind, schema-explicit). -* Derived from the registries — never hand-curated (the LEGACY_ONLY_METHODS -* table class is exactly what registry membership replaces). -*/ -function isSpecRequestMethod(method) { - return ALL_CODECS.some((codec) => codec.hasRequestMethod(method)); -} -function isSpecNotificationMethod(method) { - return ALL_CODECS.some((codec) => codec.hasNotificationMethod(method)); -} -const ALL_CODECS = [rev2025Codec, rev2026Codec]; - -//#endregion -//#region ../core-internal/src/shared/envelope.ts -/** -* Per-request `_meta` envelope claim helpers (protocol revision 2026-07-28). -* -* Pure, value-returning helpers used by the inbound HTTP classifier -* (`classifyInboundRequest`): claim detection and envelope validation with -* self-identifying issues. The envelope schema itself stays the wire layer's -* single source of truth (`RequestMetaEnvelopeSchema`); this module only maps -* its outcomes into the shapes the validation ladder emits. -* -* Claim detection is deliberately narrow: a message claims the 2026-07-28 -* envelope mechanism if and only if the reserved protocol-version `_meta` key -* is present in `params._meta`. Other reserved keys (client info, client -* capabilities, log level), a bare `progressToken`, or unrelated keys under -* the `io.modelcontextprotocol/` prefix do NOT constitute a claim on their -* own — but once the claim key is present, a malformed envelope is a -* validation error, never a silent fall back to legacy handling. -* -* The wire-exact envelope schema, the required-key set, and the per-key issue -* mapping live in the wire layer (the 2026-era codec's `validateEnvelopeMeta`). -* This module never reaches into a per-revision wire module directly. -*/ -function isPlainObject$3(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -/** The `_meta` object of a message's params, when present. */ -function src_CX2iR2pK_requestMetaOf(params) { - if (!isPlainObject$3(params)) return void 0; - const meta = params["_meta"]; - return isPlainObject$3(meta) ? meta : void 0; -} -/** -* Whether a message's params carry the per-request envelope claim: the -* reserved protocol-version `_meta` key is present (regardless of whether the -* rest of the envelope is valid — validation is a separate, later step). -*/ -function src_CX2iR2pK_hasEnvelopeClaim(params) { - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && PROTOCOL_VERSION_META_KEY in meta; -} -/** -* The protocol version named by a message's envelope claim, when the claim is -* present and carries a string value. A present claim with a non-string value -* still counts as a claim ({@linkcode hasEnvelopeClaim}); it surfaces as a -* validation issue instead of a version. -*/ -function src_CX2iR2pK_envelopeClaimVersion(params) { - const value = src_CX2iR2pK_requestMetaOf(params)?.[PROTOCOL_VERSION_META_KEY]; - return typeof value === "string" ? value : void 0; -} -/** -* Validates a request's `_meta` object as a 2026-07-28 per-request envelope -* and reports problems as self-identifying issues (which key, what problem). -* -* Returns an empty array when the envelope is valid. Missing required keys are -* reported first (as `problem: 'missing'`), then schema violations inside -* present keys, in a stable order. -*/ -function src_CX2iR2pK_validateEnvelopeMeta(meta) { - return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION).validateEnvelopeMeta(meta); -} - -//#endregion -//#region ../core-internal/src/types/schemas.ts -var schemas_exports = /* @__PURE__ */ __exportAll({ - AnnotationsSchema: () => AnnotationsSchema, - AudioContentSchema: () => AudioContentSchema, - BaseMetadataSchema: () => BaseMetadataSchema, - BaseRequestParamsSchema: () => BaseRequestParamsSchema, - BlobResourceContentsSchema: () => BlobResourceContentsSchema, - BooleanSchemaSchema: () => BooleanSchemaSchema, - CallToolRequestParamsSchema: () => CallToolRequestParamsSchema, - CallToolRequestSchema: () => CallToolRequestSchema, - CallToolResultSchema: () => auth_CUe6YdwF_CallToolResultSchema, - CancelTaskRequestSchema: () => CancelTaskRequestSchema, - CancelTaskResultSchema: () => CancelTaskResultSchema, - CancelledNotificationParamsSchema: () => CancelledNotificationParamsSchema, - CancelledNotificationSchema: () => CancelledNotificationSchema, - ClientCapabilitiesSchema: () => ClientCapabilitiesSchema, - ClientNotificationSchema: () => ClientNotificationSchema, - ClientRequestSchema: () => ClientRequestSchema, - ClientResultSchema: () => ClientResultSchema, - ClientTasksCapabilitySchema: () => ClientTasksCapabilitySchema, - CompatibilityCallToolResultSchema: () => CompatibilityCallToolResultSchema, - CompleteRequestParamsSchema: () => CompleteRequestParamsSchema, - CompleteRequestSchema: () => CompleteRequestSchema, - CompleteResultSchema: () => CompleteResultSchema, - ContentBlockSchema: () => ContentBlockSchema, - CreateMessageRequestParamsSchema: () => CreateMessageRequestParamsSchema, - CreateMessageRequestSchema: () => CreateMessageRequestSchema, - CreateMessageResultSchema: () => CreateMessageResultSchema, - CreateMessageResultWithToolsSchema: () => CreateMessageResultWithToolsSchema, - CreateTaskResultSchema: () => CreateTaskResultSchema, - CursorSchema: () => CursorSchema, - DiscoverRequestSchema: () => DiscoverRequestSchema, - DiscoverResultSchema: () => DiscoverResultSchema, - ElicitRequestFormParamsSchema: () => ElicitRequestFormParamsSchema, - ElicitRequestParamsSchema: () => ElicitRequestParamsSchema, - ElicitRequestSchema: () => ElicitRequestSchema, - ElicitRequestURLParamsSchema: () => ElicitRequestURLParamsSchema, - ElicitResultSchema: () => ElicitResultSchema, - ElicitationCompleteNotificationParamsSchema: () => ElicitationCompleteNotificationParamsSchema, - ElicitationCompleteNotificationSchema: () => ElicitationCompleteNotificationSchema, - EmbeddedResourceSchema: () => EmbeddedResourceSchema, - EmptyResultSchema: () => EmptyResultSchema, - EnumSchemaSchema: () => EnumSchemaSchema, - GetPromptRequestParamsSchema: () => GetPromptRequestParamsSchema, - GetPromptRequestSchema: () => GetPromptRequestSchema, - GetPromptResultSchema: () => GetPromptResultSchema, - GetTaskPayloadRequestSchema: () => GetTaskPayloadRequestSchema, - GetTaskPayloadResultSchema: () => GetTaskPayloadResultSchema, - GetTaskRequestSchema: () => GetTaskRequestSchema, - GetTaskResultSchema: () => GetTaskResultSchema, - IconSchema: () => IconSchema, - IconsSchema: () => IconsSchema, - ImageContentSchema: () => ImageContentSchema, - ImplementationSchema: () => ImplementationSchema, - InitializeRequestParamsSchema: () => InitializeRequestParamsSchema, - InitializeRequestSchema: () => auth_CUe6YdwF_InitializeRequestSchema, - InitializeResultSchema: () => InitializeResultSchema, - InitializedNotificationSchema: () => auth_CUe6YdwF_InitializedNotificationSchema, - JSONArraySchema: () => JSONArraySchema, - JSONObjectSchema: () => JSONObjectSchema, - JSONRPCErrorResponseSchema: () => JSONRPCErrorResponseSchema, - JSONRPCMessageSchema: () => auth_CUe6YdwF_JSONRPCMessageSchema, - JSONRPCNotificationSchema: () => JSONRPCNotificationSchema, - JSONRPCRequestSchema: () => JSONRPCRequestSchema, - JSONRPCResponseSchema: () => auth_CUe6YdwF_JSONRPCResponseSchema, - JSONRPCResultResponseSchema: () => JSONRPCResultResponseSchema, - JSONValueSchema: () => JSONValueSchema, - LegacyTitledEnumSchemaSchema: () => LegacyTitledEnumSchemaSchema, - ListChangedOptionsBaseSchema: () => ListChangedOptionsBaseSchema, - ListPromptsRequestSchema: () => ListPromptsRequestSchema, - ListPromptsResultSchema: () => ListPromptsResultSchema, - ListResourceTemplatesRequestSchema: () => ListResourceTemplatesRequestSchema, - ListResourceTemplatesResultSchema: () => ListResourceTemplatesResultSchema, - ListResourcesRequestSchema: () => ListResourcesRequestSchema, - ListResourcesResultSchema: () => ListResourcesResultSchema, - ListRootsRequestSchema: () => ListRootsRequestSchema, - ListRootsResultSchema: () => ListRootsResultSchema, - ListTasksRequestSchema: () => ListTasksRequestSchema, - ListTasksResultSchema: () => ListTasksResultSchema, - ListToolsRequestSchema: () => ListToolsRequestSchema, - ListToolsResultSchema: () => ListToolsResultSchema, - LoggingLevelSchema: () => LoggingLevelSchema, - LoggingMessageNotificationParamsSchema: () => LoggingMessageNotificationParamsSchema, - LoggingMessageNotificationSchema: () => LoggingMessageNotificationSchema, - ModelHintSchema: () => ModelHintSchema, - ModelPreferencesSchema: () => ModelPreferencesSchema, - MultiSelectEnumSchemaSchema: () => MultiSelectEnumSchemaSchema, - NotificationSchema: () => NotificationSchema, - NotificationsParamsSchema: () => NotificationsParamsSchema, - NumberSchemaSchema: () => NumberSchemaSchema, - PaginatedRequestParamsSchema: () => PaginatedRequestParamsSchema, - PaginatedRequestSchema: () => PaginatedRequestSchema, - PaginatedResultSchema: () => PaginatedResultSchema, - PingRequestSchema: () => PingRequestSchema, - PrimitiveSchemaDefinitionSchema: () => PrimitiveSchemaDefinitionSchema, - ProgressNotificationParamsSchema: () => ProgressNotificationParamsSchema, - ProgressNotificationSchema: () => ProgressNotificationSchema, - ProgressSchema: () => ProgressSchema, - ProgressTokenSchema: () => ProgressTokenSchema, - PromptArgumentSchema: () => PromptArgumentSchema, - PromptListChangedNotificationSchema: () => PromptListChangedNotificationSchema, - PromptMessageSchema: () => PromptMessageSchema, - PromptReferenceSchema: () => PromptReferenceSchema, - PromptSchema: () => PromptSchema, - ReadResourceRequestParamsSchema: () => ReadResourceRequestParamsSchema, - ReadResourceRequestSchema: () => ReadResourceRequestSchema, - ReadResourceResultSchema: () => ReadResourceResultSchema, - RelatedTaskMetadataSchema: () => RelatedTaskMetadataSchema, - RequestIdSchema: () => RequestIdSchema, - RequestMetaSchema: () => RequestMetaSchema, - RequestSchema: () => RequestSchema, - ResourceContentsSchema: () => ResourceContentsSchema, - ResourceLinkSchema: () => ResourceLinkSchema, - ResourceListChangedNotificationSchema: () => ResourceListChangedNotificationSchema, - ResourceRequestParamsSchema: () => ResourceRequestParamsSchema, - ResourceSchema: () => ResourceSchema, - ResourceTemplateReferenceSchema: () => ResourceTemplateReferenceSchema, - ResourceTemplateSchema: () => ResourceTemplateSchema, - ResourceUpdatedNotificationParamsSchema: () => ResourceUpdatedNotificationParamsSchema, - ResourceUpdatedNotificationSchema: () => ResourceUpdatedNotificationSchema, - ResultMetaObjectSchema: () => ResultMetaObjectSchema, - ResultSchema: () => ResultSchema, - RoleSchema: () => RoleSchema, - RootSchema: () => RootSchema, - RootsListChangedNotificationSchema: () => RootsListChangedNotificationSchema, - SamplingContentSchema: () => SamplingContentSchema, - SamplingMessageContentBlockSchema: () => SamplingMessageContentBlockSchema, - SamplingMessageSchema: () => SamplingMessageSchema, - ServerCapabilitiesSchema: () => ServerCapabilitiesSchema, - ServerNotificationSchema: () => ServerNotificationSchema, - ServerRequestSchema: () => ServerRequestSchema, - ServerResultSchema: () => ServerResultSchema, - ServerTasksCapabilitySchema: () => ServerTasksCapabilitySchema, - SetLevelRequestParamsSchema: () => SetLevelRequestParamsSchema, - SetLevelRequestSchema: () => SetLevelRequestSchema, - SingleSelectEnumSchemaSchema: () => SingleSelectEnumSchemaSchema, - StringSchemaSchema: () => StringSchemaSchema, - SubscribeRequestParamsSchema: () => SubscribeRequestParamsSchema, - SubscribeRequestSchema: () => SubscribeRequestSchema, - SubscriptionFilterSchema: () => SubscriptionFilterSchema, - SubscriptionsAcknowledgedNotificationParamsSchema: () => SubscriptionsAcknowledgedNotificationParamsSchema, - SubscriptionsAcknowledgedNotificationSchema: () => SubscriptionsAcknowledgedNotificationSchema, - SubscriptionsListenRequestParamsSchema: () => SubscriptionsListenRequestParamsSchema, - SubscriptionsListenRequestSchema: () => SubscriptionsListenRequestSchema, - SubscriptionsListenResultMetaSchema: () => SubscriptionsListenResultMetaSchema, - SubscriptionsListenResultSchema: () => SubscriptionsListenResultSchema, - TaskAugmentedRequestParamsSchema: () => auth_CUe6YdwF_TaskAugmentedRequestParamsSchema, - TaskCreationParamsSchema: () => TaskCreationParamsSchema, - TaskMetadataSchema: () => TaskMetadataSchema, - TaskSchema: () => TaskSchema, - TaskStatusNotificationParamsSchema: () => TaskStatusNotificationParamsSchema, - TaskStatusNotificationSchema: () => TaskStatusNotificationSchema, - TaskStatusSchema: () => TaskStatusSchema, - TextContentSchema: () => TextContentSchema, - TextResourceContentsSchema: () => TextResourceContentsSchema, - TitledMultiSelectEnumSchemaSchema: () => TitledMultiSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema: () => TitledSingleSelectEnumSchemaSchema, - ToolAnnotationsSchema: () => ToolAnnotationsSchema, - ToolChoiceSchema: () => ToolChoiceSchema, - ToolExecutionSchema: () => ToolExecutionSchema, - ToolListChangedNotificationSchema: () => ToolListChangedNotificationSchema, - ToolResultContentSchema: () => ToolResultContentSchema, - ToolSchema: () => ToolSchema, - ToolUseContentSchema: () => ToolUseContentSchema, - UnsubscribeRequestParamsSchema: () => UnsubscribeRequestParamsSchema, - UnsubscribeRequestSchema: () => UnsubscribeRequestSchema, - UntitledMultiSelectEnumSchemaSchema: () => UntitledMultiSelectEnumSchemaSchema, - UntitledSingleSelectEnumSchemaSchema: () => UntitledSingleSelectEnumSchemaSchema -}); - -//#endregion -//#region ../core-internal/src/types/guards.ts -/** -* Validates and parses an unknown value as a JSON-RPC message. -* -* Use this to validate incoming messages in custom transport implementations. -* Throws if the value does not conform to the JSON-RPC message schema. -* -* @param value - The value to validate (typically a parsed JSON object). -* @returns The validated {@linkcode JSONRPCMessage}. -* @throws If validation fails. -*/ -function parseJSONRPCMessage(value) { - return JSONRPCMessageSchema.parse(value); -} -const src_CX2iR2pK_isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success; -const src_CX2iR2pK_isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResultResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResultResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCErrorResponse}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCErrorResponse}, false otherwise. -*/ -const src_CX2iR2pK_isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode JSONRPCResponse} (either a result or error response). -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode JSONRPCResponse}, false otherwise. -*/ -const isJSONRPCResponse = (value) => JSONRPCResponseSchema.safeParse(value).success; -/** -* Checks if a value is a valid {@linkcode CallToolResult}. -* -* This is a consumer-side VALUE check against the neutral model, not a wire -* validator: a raw wire object that additionally carries wire-only members -* (e.g. `resultType`) still passes through the loose index signature. Use a -* transport-level parse to validate raw wire traffic. -* -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode CallToolResult}, false otherwise. -*/ -const isCallToolResult = (value) => { - if (typeof value !== "object" || value === null || value.content === void 0) return false; - return CallToolResultSchema.safeParse(value).success; -}; -/** -* Checks whether a value is an input-required result (protocol revision -* 2026-07-28): the multi-round-trip return shape discriminated by -* `resultType: 'input_required'`. -* -* This is a discriminator check, not a full validator — the at-least-one rule -* (`inputRequests` or `requestState`) is enforced by the `inputRequired()` -* builder and re-checked by the server seam for hand-built values. -* -* @param value - The value to check. -* @returns True if the value carries the `input_required` discriminator. -*/ -const isInputRequiredResult = (value) => typeof value === "object" && value !== null && !Array.isArray(value) && value.resultType === "input_required"; -/** -* Checks if a value is a valid {@linkcode TaskAugmentedRequestParams}. -* @param value - The value to check. -* -* @returns True if the value is a valid {@linkcode TaskAugmentedRequestParams}, false otherwise. -* -* @deprecated Recognizes 2025-11-25 task wire vocabulary, which has no SDK -* runtime; kept importable for interoperability only. -*/ -const isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success; -const src_CX2iR2pK_isInitializeRequest = (value) => InitializeRequestSchema.safeParse(value).success; -const isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success; -function assertCompleteRequestPrompt(request) { - if (request.params.ref.type !== "ref/prompt") throw new TypeError(`Expected CompleteRequestPrompt, but got ${request.params.ref.type}`); -} -function assertCompleteRequestResourceTemplate(request) { - if (request.params.ref.type !== "ref/resource") throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${request.params.ref.type}`); -} - -//#endregion -//#region ../core-internal/src/shared/mcpParamHeaders.ts -/** The fixed prefix every custom-parameter header carries. */ -const MCP_PARAM_HEADER_PREFIX = "Mcp-Param-"; -/** The schema-extension property name a tool's `inputSchema` carries. */ -const X_MCP_HEADER_KEY = "x-mcp-header"; -/** -* RFC 9110 §5.1 `token` syntax (`1*tchar`). Rejects empty, space, control -* characters (including CR/LF), and the listed delimiters. -*/ -const RFC9110_TOKEN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/; -/** -* JSON Schema `type` values the spec admits on an `x-mcp-header` property. -* -* The spec text names `integer`, `string`, `boolean` and explicitly excludes -* `number`. The published conformance referee at the pinned release ships its -* `http-custom-headers` scenario with two `type: "number"` `x-mcp-header` -* parameters and expects the client to mirror them, so `number` is accepted -* here so that the conformance gate passes; the discrepancy is tracked -* upstream. Everything else (`object`, `array`, `null`, absent) is rejected. -*/ -const PERMITTED_X_MCP_HEADER_TYPES = new Set([ - "string", - "integer", - "boolean", - "number" -]); -/** -* Scan a tool's JSON-serialized `inputSchema` for `x-mcp-header` declarations -* and validate every constraint the spec places on them. Returns either the -* collected declarations (possibly empty) or the first violated constraint. -* -* The walk descends through `properties` at any depth (the spec's "any nesting -* depth" clause). The static-reachability MUST is enforced as a structural -* sweep: every position the chain MUST NOT pass through (`items`/ -* `additionalProperties`, `oneOf`/`anyOf`/`allOf`/`not`, `if`/`then`/`else`, -* `$defs`, `$ref` targets within `$defs`) is visited too, and an -* `x-mcp-header` found anywhere on that path invalidates the schema — "an -* annotation anywhere else makes the tool definition invalid". -*/ -function src_CX2iR2pK_scanXMcpHeaderDeclarations(inputSchema) { - const declarations = []; - const seenLower = /* @__PURE__ */ new Map(); - const visit = (node, path, reachable) => { - if (node === null || typeof node !== "object") return void 0; - const schema = node; - if (X_MCP_HEADER_KEY in schema) { - if (!reachable || path.length === 0) return `${pathName(path)}: x-mcp-header is only permitted on properties statically reachable via a chain of 'properties' keys (not under items, additionalProperties, oneOf/anyOf/allOf/not, if/then/else, or $ref)`; - const raw = schema[X_MCP_HEADER_KEY]; - if (typeof raw !== "string" || raw.length === 0) return `${pathName(path)}: x-mcp-header MUST be a non-empty string`; - if (!RFC9110_TOKEN.test(raw)) return `${pathName(path)}: x-mcp-header '${raw}' is not a valid RFC 9110 token (no spaces, control characters or HTTP delimiters)`; - const type = typeof schema.type === "string" ? schema.type : void 0; - if (type === void 0 || !PERMITTED_X_MCP_HEADER_TYPES.has(type)) return `${pathName(path)}: x-mcp-header is only permitted on primitive-typed properties (string, integer, boolean); got ${type ?? ""}`; - const lower = raw.toLowerCase(); - const prior = seenLower.get(lower); - if (prior !== void 0) return `x-mcp-header '${raw}' is not case-insensitively unique (also declared as '${prior}')`; - seenLower.set(lower, raw); - declarations.push({ - path, - headerName: raw, - type - }); - } - const properties = schema.properties; - if (properties !== null && typeof properties === "object") for (const [key, child] of Object.entries(properties)) { - const fault$1 = visit(child, [...path, key], reachable); - if (fault$1 !== void 0) return fault$1; - } - for (const k of NON_REACHABLE_SUBSCHEMA_KEYWORDS) { - const sub = schema[k]; - if (sub === void 0) continue; - const branches = Array.isArray(sub) ? sub : sub !== null && typeof sub === "object" && OBJECT_VALUED_SUBSCHEMA_KEYWORDS.has(k) ? Object.values(sub) : [sub]; - for (const branch of branches) { - const fault$1 = visit(branch, [...path, `<${k}>`], false); - if (fault$1 !== void 0) return fault$1; - } - } - }; - const fault = visit(inputSchema, [], true); - return fault === void 0 ? { - valid: true, - declarations - } : { - valid: false, - reason: fault - }; -} -/** -* JSON Schema keywords whose subschemas the SEP-2243 static-reachability -* constraint excludes from the `properties`-only chain. An `x-mcp-header` -* found under any of these invalidates the tool definition. -*/ -const NON_REACHABLE_SUBSCHEMA_KEYWORDS = [ - "items", - "prefixItems", - "contains", - "additionalProperties", - "unevaluatedProperties", - "unevaluatedItems", - "propertyNames", - "patternProperties", - "dependentSchemas", - "oneOf", - "anyOf", - "allOf", - "not", - "if", - "then", - "else", - "$defs", - "definitions" -]; -/** -* Subschema-carrying keywords whose value is a `name → subschema` object -* (not a single subschema or array of subschemas). The visit branches over -* `Object.values()` for these. -*/ -const OBJECT_VALUED_SUBSCHEMA_KEYWORDS = new Set([ - "patternProperties", - "dependentSchemas", - "$defs", - "definitions" -]); -function pathName(path) { - return path.length === 0 ? "" : path.join("."); -} -const BASE64_SENTINEL_PREFIX = "=?base64?"; -const BASE64_SENTINEL_SUFFIX = "?="; -const BASE64_CANONICAL = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/; -const CANONICAL_DECIMAL = /^-?\d+(\.\d+)?$/; -/** -* Convert a primitive argument value to its string representation per the -* spec's type-conversion rules: strings pass through, integers and numbers -* become their decimal string, booleans become lowercase `'true'` / `'false'`. -* Non-finite numbers and integers outside the safe range are refused (the -* caller treats `undefined` as "do not emit a header for this value"). -*/ -function mcpParamPrimitiveToString(value) { - if (typeof value === "string") return value; - if (typeof value === "boolean") return value ? "true" : "false"; - if (typeof value === "number") { - if (!Number.isFinite(value)) return void 0; - if (Number.isInteger(value) && !Number.isSafeInteger(value)) return void 0; - return String(value); - } -} -function base64ToUtf8(b64) { - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return new TextDecoder("utf-8", { fatal: true }).decode(bytes); -} -/** -* Decode an `Mcp-Param-*` header value: when it carries the Base64 sentinel, -* the payload is decoded as UTF-8; otherwise the value is returned as-is. -* Returns `undefined` when the sentinel is present but the payload is not -* canonical Base64 (or not valid UTF-8) — the spec requires servers to reject -* such values. -*/ -function decodeMcpParamValue(value) { - if (!(value.startsWith(BASE64_SENTINEL_PREFIX) && value.endsWith(BASE64_SENTINEL_SUFFIX))) return value; - const b64 = value.slice(9, value.length - 2); - if (!BASE64_CANONICAL.test(b64)) return void 0; - try { - return base64ToUtf8(b64); - } catch { - return; - } -} -function valueAtPath(root, path) { - let node = root; - for (const key of path) { - if (node === null || typeof node !== "object") return void 0; - node = node[key]; - } - return node; -} -/** -* The header/body comparison the server performs at tool-resolution time. -* -* For each `x-mcp-header` declaration on the named tool: when the body -* `arguments` carries a value, the matching `Mcp-Param-{Name}` header MUST be -* present and decode to an equal value; when the body value is `null` or -* absent the server MUST NOT expect the header (a present header is ignored). -* A sentinel-carrying header whose payload is not canonical Base64 / valid -* UTF-8 is rejected as invalid characters. -* -* Integer-typed declarations are compared numerically (the spec's SHOULD — -* `42.0` and `42` are equal); everything else is compared as decoded strings. -* -* Returns `undefined` when every check passes, or an -* {@linkcode InboundLadderRejection} carrying the same `-32020` -* (`HeaderMismatch`) shape the inbound classifier emits for the -* standard-header cross-checks — `400 Bad Request` with the disagreeing pair -* in `data.mismatch`. -*/ -function src_CX2iR2pK_validateMcpParamHeaders(declarations, args, headers) { - for (const decl of declarations) { - const headerKey = `${MCP_PARAM_HEADER_PREFIX}${decl.headerName}`; - const headerValue = headers.get(headerKey); - const bodyRaw = valueAtPath(args, decl.path); - if (bodyRaw === void 0 || bodyRaw === null) continue; - const bodyString = mcpParamPrimitiveToString(bodyRaw); - if (bodyString === void 0) continue; - if (headerValue === null) return paramHeaderMismatchRejection("param-header-missing", headerKey, `the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)} but the ${headerKey} header is absent`); - const decoded = decodeMcpParamValue(headerValue); - if (decoded === void 0) return paramHeaderMismatchRejection("param-header-invalid-encoding", headerKey, `the ${headerKey} header carries an invalid Base64 sentinel value`); - if (!((decl.type === "integer" || decl.type === "number") && CANONICAL_DECIMAL.test(decoded) && typeof bodyRaw === "number" ? Number(decoded) === bodyRaw : decoded === bodyString)) return paramHeaderMismatchRejection("param-header-mismatch", headerKey, `the ${headerKey} header decodes to ${JSON.stringify(decoded)} but the body carries ${pathName(decl.path)}=${JSON.stringify(bodyRaw)}`); - } -} -/** -* Build the `-32020` (`HeaderMismatch`) rejection for an `Mcp-Param-*` -* disagreement. Same shape as the inbound classifier's standard-header -* cross-check mismatch (HTTP `400`, `data.mismatch` naming the disagreeing -* pair, `settled: true`); only the rung differs because this check runs at the -* pre-dispatch step against a known tool's schema rather than at the edge. -*/ -function paramHeaderMismatchRejection(cell, header, body) { - return { - kind: "reject", - rung: "param-header-validation", - cell, - httpStatus: 400, - code: HEADER_MISMATCH_ERROR_CODE, - message: `Bad Request: the request headers and body disagree: ${body}`, - data: { mismatch: { - header, - body - } }, - settled: true - }; -} - -//#endregion -//#region ../core-internal/src/shared/inboundClassification.ts -/** -* Inbound HTTP request classification and the inbound validation ladder -* (protocol revision 2026-07-28). -* -* `classifyInboundRequest` is the body-primary era predicate for an HTTP -* entry that serves both protocol eras on one endpoint. It is evaluated -* exactly once, at the entry boundary, on the already-parsed request body: -* -* - `initialize` is a legacy-era request by definition (the modern era has no -* `initialize` handshake) — unless it carries a valid envelope claim naming -* a modern revision, in which case the claim wins and the request is -* classified like any other enveloped request (the modern era then answers -* it with method-not-found, exactly like every other method it does not -* define). -* - A request whose `params._meta` carries the reserved protocol-version key -* claims the per-request envelope mechanism and classifies into the era the -* named revision belongs to (a malformed envelope behind a present claim is -* a validation error, never a silent fall back to legacy handling). -* - A request without a claim is legacy-era traffic. -* - The `MCP-Protocol-Version` header is a cross-check only: it never -* upgrades or downgrades a body-derived classification, and a disagreement -* between header and body is an explicit ladder outcome. -* - Notifications carry no envelope claim of their own under the current -* spec, so for notification POSTs without a body claim the modern header is -* determinative; the `Mcp-Method` header is validated against the body when -* the message classifies modern and is never enforced on legacy traffic. -* A notification that does carry a claim is treated body-primary like a -* request, and a malformed claim is rejected the same way a request's -* malformed claim is — never silently resolved against the header. -* The notification-POST header cross-checks here are an SDK-defensive -* posture, not a spec requirement: the spec leaves header rules for posted -* notifications undefined (core client notifications do not occur over -* Streamable HTTP); applying the request rules symmetrically is what an -* ecosystem custom-notification POST expects, and the −32020 cells stay -* passing for them. -* - `GET`/`DELETE` (and any other non-`POST` method) are body-less 2025-era -* session operations: the modern era is `POST`-only, so they are routed to -* legacy serving when it is configured and rejected otherwise. -* - Array (batch) bodies are classified element-wise: an array containing a -* modern-claiming or invalid element is rejected, an all-legacy array is -* legacy traffic unchanged, and a single-element array is still an array. -* -* The classifier returns plain values (it never throws and never touches a -* transport): a routing outcome (`legacy`/`modern`) or a ladder rejection -* carrying the JSON-RPC error to emit and the HTTP status to emit it with. -* Legacy routing outcomes deliberately carry NO `MessageClassification` — -* legacy and hand-wired traffic is never classified, which keeps its -* dispatch behavior byte-identical to today's. -* -* Error codes for the modern-path rejection cells follow the published -* conformance suite (and the spec text it asserts): -* -* - A header/body cross-check mismatch (the `MCP-Protocol-Version` header -* disagreeing with the body, or the `Mcp-Method` header disagreeing with the -* body method) is rejected with `-32020` (`HeaderMismatch`) on HTTP 400. -* - A request whose protocol-version header names a modern revision but whose -* body carries no `_meta` envelope claim — including an envelope present but -* missing the required protocol-version key — is rejected with `-32602` -* (invalid params) naming the missing key(s), on HTTP 400. -* -* Should a future spec revision or conformance release change these -* assignments, the affected cells are re-derived against that release; the -* `settled` flag on {@linkcode InboundLadderRejection} stays available to mark -* a cell provisional again while such a change is in flight. -*/ -/** -* The error code emitted for header/body cross-check mismatches: the -* `MCP-Protocol-Version` header disagreeing with the body's envelope claim (or -* with the body's classification), and the `Mcp-Method` header disagreeing -* with the body method. -* -* `-32020` is the draft schema's `HEADER_MISMATCH` constant (the SEP-2243 -* `HeaderMismatch` code; the spec requires HTTP 400 for it), as also asserted -* by the published conformance suite for header-validation failures. It has no -* {@linkcode ProtocolErrorCode} member because it is not part of the 2025-era -* wire vocabulary; the validation ladder is its only emitter. -*/ -const HEADER_MISMATCH_ERROR_CODE = -32020; -/** -* The inbound validation ladder, expressed as data rather than control flow. -* -* The edge rungs are evaluated by {@linkcode classifyInboundRequest}; the -* dispatch rungs are evaluated by the protocol layer once the classified -* message is injected into a per-request server instance (the era registry -* gate, the envelope requiredness check, and per-method params validation). -* The client-capability rung is evaluated by the HTTP entry itself, -* pre-dispatch, on the validated envelope the classifier produced — see that -* rung's rationale for the ordering caveat. The order is the precedence: a -* request that fails several rungs is answered by the earliest one. -*/ -const INBOUND_VALIDATION_LADDER = [ - { - rung: "http-method", - order: 1, - evaluatedAt: "edge", - codes: [-32e3], - conformance: [], - rationale: "The modern era is POST-only; GET/DELETE are body-less 2025-era session operations and are method-routed to legacy serving (405 when legacy serving is not configured), before any body is read." - }, - { - rung: "jsonrpc-shape", - order: 2, - evaluatedAt: "edge", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest], - conformance: ["server-stateless"], - rationale: "The body must be a JSON-RPC request or notification: posted responses and batch arrays containing a modern or invalid element are rejected before classification (element-wise batch rule); all-legacy arrays stay legacy traffic." - }, - { - rung: "era-classification", - order: 3, - evaluatedAt: "edge", - codes: [HEADER_MISMATCH_ERROR_CODE, src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion], - conformance: [ - "server-stateless", - "http-header-validation", - "http-custom-header-server-validation" - ], - rationale: "Body-primary era classification with the protocol-version header as a cross-check; a header/body disagreement is rejected with -32020 (HeaderMismatch), and an envelope-less request on a modern-only endpoint is answered with the unsupported-protocol-version error naming the supported revisions." - }, - { - rung: "envelope", - order: 4, - evaluatedAt: "edge", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: ["server-stateless"], - rationale: "A present envelope claim with a malformed envelope — and a missing envelope on a request whose protocol-version header names a modern revision — is an invalid-params rejection naming the offending or missing key(s); never a silent fall back to legacy handling. This is the only place an invalid-params rejection maps to HTTP 400." - }, - { - rung: "method-registry", - order: 5, - evaluatedAt: "dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound], - conformance: ["server-stateless"], - rationale: "Method existence outranks parameter validity: a method absent from the negotiated revision’s registry (or with no handler installed) answers method-not-found before params or capabilities are looked at." - }, - { - rung: "request-params", - order: 6, - evaluatedAt: "dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.InvalidParams], - conformance: [], - rationale: "Per-method params validation; emitted in-band by the dispatch layer (HTTP 200), never via the ladder status table." - }, - { - rung: "standard-header-validation", - order: 7, - evaluatedAt: "pre-dispatch", - codes: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-header-validation"], - rationale: "SEP-2243 standard `Mcp-Method` / `Mcp-Name` headers — presence, sentinel decoding, and `Mcp-Name` ↔ body cross-check — are validated by the HTTP entry on a modern-classified request after the supported-revision gate and before dispatch. The classifier’s own header-mismatch cells (protocol-version, `Mcp-Method` mismatch) stay on the edge `era-classification` rung; this rung carries the entry-layer presence/`Mcp-Name` half. Evaluated before the capability gate, the factory call, and the `Mcp-Param-*` rung so a request that fails several rungs is answered by the standard-header rung first. The documented order (after method-registry 5 and request-params 6) is NOT the observed precedence: serveModern evaluates this rung immediately after the supported-revision gate, so a request that also fails a dispatch rung is answered here before the dispatch rungs (5–6) are consulted." - }, - { - rung: "client-capabilities", - order: 8, - evaluatedAt: "pre-dispatch", - codes: [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability], - conformance: ["server-stateless"], - rationale: "The capability requirement is checked by the HTTP entry, pre-dispatch, against the validated envelope the classifier produced — pinning the spec-mandated HTTP 400 independently of how dispatch- and handler-produced errors are mapped. The documented order (after method resolution and params validation) is preserved observably only while the requirement table is empty: once a served method gains a requirement entry, a request that is missing the capability and would also fail a dispatch rung is answered by this gate first, so the entry must consult the method registry before the gate if the documented precedence is to stay observable." - }, - { - rung: "param-header-validation", - order: 9, - evaluatedAt: "pre-dispatch", - codes: [HEADER_MISMATCH_ERROR_CODE], - conformance: ["http-custom-header-server-validation"], - rationale: "SEP-2243 `Mcp-Param-*` headers are validated against the named tool’s `x-mcp-header` declarations and the body `arguments` after the tool registry is known and before dispatch reaches the handler; a missing/disagreeing/malformed header is rejected 400 / -32020 with the same shape as the standard-header cross-checks. The documented order (after method resolution and params validation) is preserved observably only when the body `arguments` would otherwise validate: the check runs pre-dispatch, so a `tools/call` that fails BOTH this rung and a dispatch-time rung (e.g. order-6 `request-params`, -32602) is answered by this gate first with 400 / -32020, not by the earlier-ordered rung." - } -]; -/** -* HTTP status for ladder-originated JSON-RPC error codes. -* -* Keyed on origin, not on the bare code: this table only applies to errors -* the ladder (or a pre-handler protocol gate) produced. Errors produced by -* request handlers — whatever their code — stay in-band on HTTP 200, and are -* never mapped to an HTTP status by this table; in particular `-32603` and -* domain-specific codes never become a blanket 500. The single exception is -* `MissingRequiredClientCapability` (-32021) — see -* {@linkcode httpStatusForErrorCode}. -* -* `-32602` (invalid params) deliberately has NO entry: the only invalid-params -* rejection that maps to HTTP 400 is the classifier's own envelope rung -* short-circuit, which carries its HTTP status directly. A dispatch- or -* handler-produced invalid-params error is always in-band. -*/ -const src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS = { - [src_CX2iR2pK_ProtocolErrorCode.ParseError]: 400, - [src_CX2iR2pK_ProtocolErrorCode.InvalidRequest]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MethodNotFound]: 404, - [src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion]: 400, - [src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability]: 400, - [HEADER_MISMATCH_ERROR_CODE]: 400 -}; -/** -* The HTTP status to answer a JSON-RPC error with, keyed on the error's -* origin. `in-band` errors (anything produced by a request handler) are -* HTTP 200 — the JSON-RPC error response is the payload, not an HTTP -* failure — with ONE exception: `MissingRequiredClientCapability` (-32021), -* whose 400 the spec mandates on the error itself with no origin condition, -* and which the SDK genuinely produces after dispatch (the `input_required` -* capability gate). A handler relaying some downstream peer's `-32020`/`-32022` -* is NOT that peer's spec error and stays in-band like every other handler -* code. `ladder` errors map through {@linkcode LADDER_ERROR_HTTP_STATUS}. -* -* The per-request transport intentionally does NOT delegate to this function: -* its `?? 400` ladder fallback is only correct for entry-gate codes known to -* the table, and would wrongly map dispatch-window errors outside it (a -* window `-32602` must stay in-band on 200). The transport indexes the table -* directly; keep the two in agreement when editing either. -*/ -function src_CX2iR2pK_httpStatusForErrorCode(code, origin) { - if (origin === "in-band") return code === src_CX2iR2pK_ProtocolErrorCode.MissingRequiredClientCapability ? 400 : 200; - return src_CX2iR2pK_LADDER_ERROR_HTTP_STATUS[code] ?? 400; -} -function src_CX2iR2pK_rejection(rung, cell, httpStatus, error, settled) { - return { - kind: "reject", - rung, - cell, - httpStatus, - code: error.code, - message: error.message, - ...error.data !== void 0 && { data: error.data }, - settled - }; -} -function crossCheckMismatch(cell, header, body, rung = "era-classification") { - return src_CX2iR2pK_rejection(rung, cell, 400, new src_CX2iR2pK_ProtocolError(HEADER_MISMATCH_ERROR_CODE, `Bad Request: the request headers and body disagree: ${body}`, { mismatch: { - header, - body - } }), true); -} -/** -* The methods whose body carries a `params.name` / `params.uri` value the -* `Mcp-Name` header must mirror, and which body field supplies it (SEP-2243 -* § Standard Request Headers, `Required For` column). -*/ -const MCP_NAME_HEADER_SOURCE = (/* unused pure expression or super */ null && ({ - "tools/call": "name", - "prompts/get": "name", - "resources/read": "uri" -})); -/** Strip RFC 9110 optional whitespace (SP / HTAB) around a field value in linear time. */ -function stripHttpOws(value) { - let start = 0; - while (start < value.length) { - const code = value.codePointAt(start); - if (code !== 9 && code !== 32) break; - start += 1; - } - let end = value.length; - while (end > start) { - const code = value.codePointAt(end - 1); - if (code !== 9 && code !== 32) break; - end -= 1; - } - return start === 0 && end === value.length ? value : value.slice(start, end); -} -/** -* SEP-2243 standard-header server-side validation, evaluated by the HTTP -* entry on a modern-classified request immediately after -* {@linkcode classifyInboundRequest} returns a modern route. -* -* Returns the `-32020` (`HeaderMismatch`) ladder rejection (HTTP `400`, -* `standard-header-validation` rung — the same shape -* {@linkcode classifyInboundRequest} already emits on the edge -* `era-classification` rung for the `MCP-Protocol-Version` and -* `Mcp-Method` *mismatch* cells) when: -* -* - the required `Mcp-Method` header is absent; -* - the required `Mcp-Name` header is absent on a `tools/call`, -* `prompts/get`, or `resources/read` request whose body carries the -* `params.name` / `params.uri` value the header mirrors; -* - the `Mcp-Name` header carries an invalid `=?base64?…?=` sentinel; or -* - the (decoded) `Mcp-Name` value disagrees with the body's -* `params.name` / `params.uri`. -* -* Returns `undefined` (pass) for notifications (the spec table reads -* "All requests"), for methods that have no `Mcp-Name` source, and when the -* headers agree with the body. Never enforced on legacy traffic — the entry -* only calls this on a modern route. -* -* Kept separate from {@linkcode classifyInboundRequest} so that a body-only -* call to the classifier (no headers passed) keeps routing a modern request -* unchanged: the classifier remains a pure body-primary router, and this -* function is the presence/`Mcp-Name` half of the standard-header rung the -* entry layers on top. -*/ -function src_CX2iR2pK_validateStandardRequestHeaders(request, route) { - if (route.messageKind !== "request") return; - const method = route.message.method; - if (request.mcpMethodHeader === void 0) return crossCheckMismatch("method-header-missing", "(missing)", `the body names method ${method} but the required Mcp-Method header is absent`, "standard-header-validation"); - const sourceField = Object.hasOwn(MCP_NAME_HEADER_SOURCE, method) ? MCP_NAME_HEADER_SOURCE[method] : void 0; - if (sourceField === void 0) return; - const sourceValue = route.message.params?.[sourceField]; - const bodyValue = typeof sourceValue === "string" ? sourceValue : void 0; - if (request.mcpNameHeader === void 0) { - if (bodyValue === void 0) return; - return crossCheckMismatch("name-header-missing", "(missing)", `the body carries params.${sourceField}="${bodyValue}" but the required Mcp-Name header is absent`, "standard-header-validation"); - } - const normalizedNameHeader = stripHttpOws(request.mcpNameHeader); - const decoded = decodeMcpParamValue(normalizedNameHeader); - if (decoded === void 0) return crossCheckMismatch("name-header-invalid-encoding", normalizedNameHeader, "the Mcp-Name header carries an invalid Base64 sentinel value", "standard-header-validation"); - if (bodyValue !== void 0 && decoded !== bodyValue) return crossCheckMismatch("name-header-mismatch", normalizedNameHeader, `the body carries params.${sourceField}="${bodyValue}" but the Mcp-Name header names "${decoded}"`, "standard-header-validation"); -} -function isPlainObject$2(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function classificationForClaim(claimedVersion) { - if (claimedVersion === void 0) return { era: "modern" }; - return { - era: isModernProtocolVersion(claimedVersion) ? "modern" : "legacy", - revision: claimedVersion - }; -} -/** -* Whether a request's params carry a per-request envelope claim that is both -* well-formed and names a modern protocol revision. -* -* Used by the `initialize` precedence rule: only such a claim overrides the -* `initialize` ⇒ legacy-handshake classification — a request carrying a valid -* modern envelope is a modern request regardless of its method name, and the -* modern era then answers `initialize` exactly like any other method it does -* not define (method-not-found). A malformed claim, or one naming a pre-2026 -* revision, keeps the legacy-handshake routing unchanged. -* -* Exported on the core internal barrel for the stdio serving entry, which -* applies the same precedence rule to a connection's opening message; not -* public API. -*/ -function src_CX2iR2pK_carriesValidModernEnvelopeClaim(params) { - if (!src_CX2iR2pK_hasEnvelopeClaim(params)) return false; - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0 || !isModernProtocolVersion(claimedVersion)) return false; - const meta = src_CX2iR2pK_requestMetaOf(params); - return meta !== void 0 && src_CX2iR2pK_validateEnvelopeMeta(meta).length === 0; -} -function classifyBatch(body) { - if (body.length === 0) return src_CX2iR2pK_rejection("jsonrpc-shape", "empty-batch", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: empty JSON-RPC batch"), true); - for (const element of body) { - if (src_CX2iR2pK_hasEnvelopeClaim(isPlainObject$2(element) ? element["params"] : void 0)) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-modern-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches may not contain requests for protocol revision 2026-07-28 or later"), true); - if (!(src_CX2iR2pK_isJSONRPCRequest(element) || src_CX2iR2pK_isJSONRPCNotification(element) || src_CX2iR2pK_isJSONRPCResultResponse(element) || src_CX2iR2pK_isJSONRPCErrorResponse(element))) return src_CX2iR2pK_rejection("jsonrpc-shape", "batch-with-invalid-element", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batch contains an invalid message"), true); - } - return { - kind: "legacy", - reason: "batch" - }; -} -function classifyRequestBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (method === "initialize" && !src_CX2iR2pK_carriesValidModernEnvelopeClaim(params)) { - if (headerNamesModern) return crossCheckMismatch("initialize-with-modern-header", headerVersion, "an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header"); - const requestedVersion = isPlainObject$2(params) && typeof params["protocolVersion"] === "string" ? params["protocolVersion"] : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return src_CX2iR2pK_rejection("envelope", "envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${firstIssue.key}: ${firstIssue.problem}`, { envelope: firstIssue }), true); - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (headerVersion !== void 0 && claimedVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("header-body-version-mismatch", headerVersion, `the body envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("method-header-mismatch", request.mcpMethodHeader, `the body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "request", - message: body, - classification: classificationForClaim(claimedVersion) - }; - } - if (headerNamesModern) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const missingFromEnvelope = src_CX2iR2pK_validateEnvelopeMeta(meta ?? {}).filter((issue) => issue.problem === "missing").map((issue) => issue.key); - const missing = meta === void 0 ? ["_meta"] : missingFromEnvelope.length > 0 ? missingFromEnvelope : [PROTOCOL_VERSION_META_KEY]; - return src_CX2iR2pK_rejection("envelope", "modern-header-without-claim", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params: the MCP-Protocol-Version header names protocol revision ${headerVersion}, but the request is missing the required per-request envelope key(s): ${missing.join(", ")}`, { envelope: { missing } }), true); - } - return { - kind: "legacy", - reason: "no-claim", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -function classifyNotificationBody(request, body) { - const params = body.params; - const method = body.method; - const headerVersion = request.protocolVersionHeader; - const headerNamesModern = headerVersion !== void 0 && isModernProtocolVersion(headerVersion); - if (src_CX2iR2pK_hasEnvelopeClaim(params)) { - const claimedVersion = src_CX2iR2pK_envelopeClaimVersion(params); - if (claimedVersion === void 0) { - const meta = src_CX2iR2pK_requestMetaOf(params); - const claimIssue = (meta === void 0 ? [] : src_CX2iR2pK_validateEnvelopeMeta(meta)).find((issue) => issue.key === PROTOCOL_VERSION_META_KEY) ?? { - key: PROTOCOL_VERSION_META_KEY, - problem: "expected a protocol version string" - }; - return src_CX2iR2pK_rejection("envelope", "notification-envelope-invalid", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid _meta envelope for protocol revision 2026-07-28: ${claimIssue.key}: ${claimIssue.problem}`, { envelope: claimIssue }), true); - } - if (headerVersion !== void 0 && headerVersion !== claimedVersion) return crossCheckMismatch("notification-header-body-version-mismatch", headerVersion, `the notification envelope names protocol version ${claimedVersion} but the MCP-Protocol-Version header names ${headerVersion}`); - const classification = classificationForClaim(claimedVersion); - if (classification.era === "modern" && request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification - }; - } - if (headerNamesModern) { - if (request.mcpMethodHeader !== void 0 && request.mcpMethodHeader !== method) return crossCheckMismatch("notification-method-header-mismatch", request.mcpMethodHeader, `the notification body names method ${method} but the Mcp-Method header names ${request.mcpMethodHeader}`); - return { - kind: "modern", - messageKind: "notification", - message: body, - classification: { - era: "modern", - revision: headerVersion - } - }; - } - return { - kind: "legacy", - reason: "notification", - ...headerVersion !== void 0 && { requestedVersion: headerVersion } - }; -} -/** -* Classifies one inbound HTTP request for dual-era serving. -* -* The body-primary predicate, evaluated once at the entry boundary: see the -* module documentation for the rules. Returns a routing outcome (`legacy` or -* `modern`) or a ladder rejection; it never throws. -*/ -function src_CX2iR2pK_classifyInboundRequest(request) { - request = { - ...request, - ...request.protocolVersionHeader !== void 0 && { protocolVersionHeader: stripHttpOws(request.protocolVersionHeader) }, - ...request.mcpMethodHeader !== void 0 && { mcpMethodHeader: stripHttpOws(request.mcpMethodHeader) }, - ...request.mcpNameHeader !== void 0 && { mcpNameHeader: stripHttpOws(request.mcpNameHeader) } - }; - if (request.httpMethod.toUpperCase() !== "POST") return { - kind: "legacy", - reason: "http-method" - }; - const body = request.body; - if (Array.isArray(body)) return classifyBatch(body); - if (src_CX2iR2pK_isJSONRPCResultResponse(body) || src_CX2iR2pK_isJSONRPCErrorResponse(body)) return { - kind: "legacy", - reason: "response" - }; - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCRequest(body)) return classifyRequestBody(request, body); - if (isPlainObject$2(body) && src_CX2iR2pK_isJSONRPCNotification(body)) return classifyNotificationBody(request, body); - return src_CX2iR2pK_rejection("jsonrpc-shape", "invalid-json-rpc-body", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: the request body is not a valid JSON-RPC message"), true); -} -/** -* The rejection a modern-only endpoint (no legacy serving configured) -* answers a legacy-classified request with. -* -* - Envelope-less requests (including `initialize`) are answered with the -* unsupported-protocol-version error carrying the endpoint's supported -* versions and echoing the version the request named (when it named one — -* `requested` is omitted rather than fabricated when the request named no -* version at all), so a legacy client can discover what the endpoint serves -* from the error alone. -* - Posted responses and batch arrays are invalid requests on the modern era. -* - Non-`POST` methods are not allowed. -* - Legacy-classified notifications return `undefined`: the caller answers -* 202 with no body and does not dispatch the notification (accept-and-drop). -*/ -function src_CX2iR2pK_modernOnlyStrictRejection(route, supportedVersions) { - switch (route.reason) { - case "http-method": return src_CX2iR2pK_rejection("http-method", "modern-only-method-not-allowed", 405, new src_CX2iR2pK_ProtocolError(-32e3, "Method not allowed."), true); - case "batch": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-batch-not-supported", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC batches are not supported by this endpoint"), true); - case "response": return src_CX2iR2pK_rejection("jsonrpc-shape", "modern-only-response-post", 400, new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidRequest, "Bad Request: JSON-RPC responses cannot be posted to this endpoint"), true); - case "notification": return; - case "initialize": - case "no-claim": { - const requested = route.requestedVersion; - return src_CX2iR2pK_rejection("era-classification", "modern-only-missing-envelope", 400, requested === void 0 ? new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, "Unsupported protocol version: the request did not name a protocol version", { supported: [...supportedVersions] }) : new src_CX2iR2pK_UnsupportedProtocolVersionError({ - supported: [...supportedVersions], - requested - }), true); - } - } -} - -//#endregion -//#region ../core-internal/src/util/schema.ts -/** -* Internal Zod schema utilities for protocol handling. -* These are used internally by the SDK for protocol message validation. -*/ -/** -* Parses data against a Zod schema (synchronous). -* Returns a discriminated union with success/error. -*/ -function parseSchema(schema, data) { - return parse_safeParse(schema, data); -} -/** -* Union of the declared shape keys across several Zod object schemas. -*/ -function shapeKeys(schemas) { - return new Set(schemas.flatMap((schema) => Object.keys(schema.shape))); -} - -//#endregion -//#region ../core-internal/src/util/standardSchema.ts -/** -* Standard Schema utilities for user-provided schemas. -* Supports Zod v4, Valibot, ArkType, and other Standard Schema implementations. -* @see https://standardschema.dev -*/ -function isStandardSchema(schema) { - if (schema == null) return false; - const schemaType = typeof schema; - if (schemaType !== "object" && schemaType !== "function") return false; - if (!("~standard" in schema)) return false; - return typeof schema["~standard"]?.validate === "function"; -} -let warnedZodFallback = false; -/** JSON Schema draft targeted by every conversion; shared so pattern references above stay in lockstep. */ -const JSON_SCHEMA_CONVERSION_TARGET = "draft-2020-12"; -/** -* Converts a StandardSchema to JSON Schema for use as an MCP tool/prompt schema. -* -* MCP requires `type: "object"` at the root of tool `inputSchema` and prompt -* argument schemas; `outputSchema` may have any JSON Schema root (SEP-2106). -* Zod's discriminated unions emit `{oneOf: [...]}` without a top-level `type`, -* so for `io: 'input'` this function defaults `type` to `"object"` when absent -* and throws on an explicit non-object `type` (e.g. `z.string()`). For -* `io: 'output'` a non-object root is returned as-is; the `"object"` default is -* applied only when the root is provably object-shaped. -*/ -function standardSchemaToJsonSchema(schema, io = "input") { - const std = schema["~standard"]; - let result; - if (std.jsonSchema) result = std.jsonSchema[io]({ target: JSON_SCHEMA_CONVERSION_TARGET }); - else if (std.vendor === "zod") { - if (!("_zod" in schema)) throw new Error("Schema appears to be from zod 3, which the SDK cannot convert to JSON Schema. Upgrade to zod >=4.2.0, or wrap your JSON Schema with fromJsonSchema()."); - if (!warnedZodFallback) { - warnedZodFallback = true; - console.warn("[mcp-sdk] Your zod version does not implement `~standard.jsonSchema` (added in zod 4.2.0). Falling back to z.toJSONSchema(). Upgrade to zod >=4.2.0 to silence this warning."); - } - result = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io - }); - } else throw new Error(`Schema library "${std.vendor}" does not implement StandardJSONSchemaV1 (\`~standard.jsonSchema\`). Upgrade to a version that does, or wrap your JSON Schema with fromJsonSchema().`); - if (io === "output") { - if (result.type !== void 0) return result; - return isProvablyObjectShapedRoot(result) ? { - type: "object", - ...result - } : result; - } - if (result.type !== void 0 && result.type !== "object") throw new Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(result.type)}). Wrap your schema in z.object({...}) or equivalent.`); - return { - type: "object", - ...result - }; -} -/** -* A typeless JSON Schema root is "provably object-shaped" when either it carries object keywords -* directly (`properties`/`patternProperties`/`additionalProperties`/`required`), or it is a -* composition (`oneOf`/`anyOf`/`allOf`) whose every member is itself `type:'object'` or recursively -* provably object-shaped (e.g. a nested `discriminatedUnion`). `$ref` is not followed. Used to -* decide whether stamping `type:'object'` is safe (redundant-but-valid) versus self-contradictory. -*/ -function isProvablyObjectShapedRoot(schema) { - if ("properties" in schema || "patternProperties" in schema || "additionalProperties" in schema || "required" in schema) return true; - for (const key of [ - "oneOf", - "anyOf", - "allOf" - ]) { - const members = schema[key]; - if (Array.isArray(members) && members.length > 0) return members.every((m) => m !== null && typeof m === "object" && (m.type === "object" || isProvablyObjectShapedRoot(m))); - } - return false; -} -function formatIssue(issue) { - if (!issue.path?.length) return issue.message; - return `${issue.path.map((p) => String(typeof p === "object" ? p.key : p)).join(".")}: ${issue.message}`; -} -async function validateStandardSchema(schema, data) { - const result = await schema["~standard"].validate(data); - if (result.issues && result.issues.length > 0) return { - success: false, - error: result.issues.map((i) => formatIssue(i)).join(", ") - }; - return { - success: true, - data: result.value - }; -} -function zodEmittedPattern(schema) { - const jsonSchema = toJSONSchema(schema, { - target: JSON_SCHEMA_CONVERSION_TARGET, - io: "input" - }); - return typeof jsonSchema.pattern === "string" ? jsonSchema.pattern : void 0; -} -const DATETIME_FRACTION_DIGITS = /\\\.\\d\{(\d+)\}/; -function datetimeReferenceSchemas(pattern) { - const fractionDigits = DATETIME_FRACTION_DIGITS.exec(pattern); - const precisions = [ - void 0, - -1, - 0 - ]; - if (fractionDigits) precisions.push(Number(fractionDigits[1])); - return [false, true].flatMap((local) => [false, true].flatMap((offset) => precisions.map((precision) => iso_datetime({ - local, - offset, - precision - })))); -} -function referencePatternsForFormat(format, pattern) { - let referenceSchemas; - switch (format) { - case "email": - referenceSchemas = [schemas_email()]; - break; - case "uri": - referenceSchemas = [schemas_url()]; - break; - case "date": - referenceSchemas = [iso_date()]; - break; - case "date-time": - referenceSchemas = datetimeReferenceSchemas(pattern); - break; - } - return new Set(referenceSchemas.map((schema) => zodEmittedPattern(schema)).filter((emitted) => emitted !== void 0)); -} -/** Whether `pattern` is the library's own realization of `format` (droppable) rather than a user customization. */ -function isLibraryFormatPattern(format, pattern, vendor) { - if (vendor !== "zod") return true; - return referencePatternsForFormat(format, pattern).has(pattern); -} -function promptArgumentsFromStandardSchema(schema) { - const jsonSchema = standardSchemaToJsonSchema(schema, "input"); - const properties = jsonSchema.properties || {}; - const required = jsonSchema.required || []; - return Object.entries(properties).map(([name, prop]) => ({ - name, - description: prop?.description, - required: required.includes(name) - })); -} - -//#endregion -//#region ../core-internal/src/shared/elicitation.ts -function isJsonObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -function convertStandardElicitationSchema(schema) { - try { - return standardSchemaToJsonSchema(schema, "input"); - } catch (error) { - const detail = error instanceof Error ? error.message : String(error); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema must describe an object with flat primitive properties: ${detail}`); - } -} -const ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS = new Set([ - "$comment", - "deprecated", - "description", - "examples", - "readOnly", - "title", - "writeOnly" -]); -function isAnnotationOnlyJsonSchemaKeyword(key) { - return ANNOTATION_ONLY_JSON_SCHEMA_KEYWORDS.has(key) || key.startsWith("x-"); -} -const ROOT_KEYS = new Set(["$schema", ...Object.keys(ElicitRequestFormParamsSchema.shape.requestedSchema.shape)]); -const PROPERTY_KEYS_BY_TYPE = { - string: shapeKeys([ - StringSchemaSchema, - UntitledSingleSelectEnumSchemaSchema, - TitledSingleSelectEnumSchemaSchema, - LegacyTitledEnumSchemaSchema - ]), - number: shapeKeys([NumberSchemaSchema]), - integer: shapeKeys([NumberSchemaSchema]), - boolean: shapeKeys([BooleanSchemaSchema]), - array: shapeKeys([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]) -}; -const SUPPORTED_STRING_FORMATS = new Set(StringSchemaSchema.shape.format.unwrap().options); -/** Walks one property node: keeps grammar keys, drops the library format pattern, rejects unknown constraints. */ -function walkProperty(node, path, vendor, unsupported) { - if (!isJsonObject(node)) return node; - const allowedKeys = typeof node.type === "string" && Object.hasOwn(PROPERTY_KEYS_BY_TYPE, node.type) ? PROPERTY_KEYS_BY_TYPE[node.type] : void 0; - if (allowedKeys === void 0) return node; - const pruned = {}; - for (const [key, value] of Object.entries(node)) if (allowedKeys.has(key) || isAnnotationOnlyJsonSchemaKeyword(key)) pruned[key] = value; - else if (key === "pattern" && node.type === "string" && typeof node.format === "string") { - if (!SUPPORTED_STRING_FORMATS.has(node.format)) pruned[key] = value; - else if (typeof value !== "string" || !isLibraryFormatPattern(node.format, value, vendor)) unsupported.push(`${path}.${key}`); - } else unsupported.push(`${path}.${key}`); - return pruned; -} -/** Walks the schema root: keeps the spec root keys, drops annotations, rejects the rest. */ -function walkRequestedSchema(converted, vendor) { - const pruned = {}; - const unsupported = []; - for (const [key, value] of Object.entries(converted)) if (key === "properties" && isJsonObject(value)) pruned[key] = Object.fromEntries(Object.entries(value).map(([name, node]) => [name, walkProperty(node, `properties.${name}`, vendor, unsupported)])); - else if (ROOT_KEYS.has(key)) pruned[key] = value; - else if (!isAnnotationOnlyJsonSchemaKeyword(key)) unsupported.push(key); - if (unsupported.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${unsupported.join(", ")}`); - return pruned; -} -/** Names the properties that fail value validation, instead of surfacing a raw union dump. */ -function describeUnsupportedProperties(pruned, fallback) { - if (!isJsonObject(pruned.properties)) return fallback; - const offenders = Object.entries(pruned.properties).filter(([, node]) => !parseSchema(PrimitiveSchemaDefinitionSchema, node).success).map(([name]) => `properties.${name}`); - return offenders.length > 0 ? offenders.join(", ") : fallback; -} -function findDroppedConstraintPaths(original, parsed, path = "") { - if (Array.isArray(original) && Array.isArray(parsed)) return original.flatMap((item, index) => findDroppedConstraintPaths(item, parsed[index], `${path}[${index}]`)); - if (!isJsonObject(original) || !isJsonObject(parsed)) return []; - return Object.entries(original).flatMap(([key, value]) => { - const childPath = path ? `${path}.${key}` : key; - if (!Object.prototype.hasOwnProperty.call(parsed, key)) return isAnnotationOnlyJsonSchemaKeyword(key) ? [] : [childPath]; - return findDroppedConstraintPaths(value, parsed[key], childPath); - }); -} -/** Converts an authoring-friendly elicitation input into its wire-ready form. */ -function normalizeElicitInputParams(input) { - if (!isStandardSchema(input.requestedSchema)) return { - ...input, - mode: "form", - requestedSchema: input.requestedSchema - }; - const vendor = input.requestedSchema["~standard"].vendor; - const pruned = walkRequestedSchema(convertStandardElicitationSchema(input.requestedSchema), vendor); - const parsed = parseSchema(ElicitRequestFormParamsSchema.shape.requestedSchema, pruned); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema only supports flat primitive properties (string, number, integer, boolean, and string enums): ${describeUnsupportedProperties(pruned, parsed.error.message)}`); - const droppedConstraints = findDroppedConstraintPaths(pruned, parsed.data); - if (droppedConstraints.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema contains unsupported JSON Schema constraint(s) after Standard Schema conversion: ${droppedConstraints.join(", ")}`); - const danglingRequired = (parsed.data.required ?? []).filter((key) => !Object.prototype.hasOwnProperty.call(parsed.data.properties, key)); - if (danglingRequired.length > 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation requestedSchema lists required properties that are not defined in properties: ${danglingRequired.join(", ")}`); - return { - ...input, - mode: "form", - requestedSchema: parsed.data - }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequired.ts -/** -* Authoring helpers for multi-round-trip requests (protocol revision -* 2026-07-28). -* -* A handler for one of the multi-round-trip methods (`tools/call`, -* `prompts/get`, `resources/read`) requests additional client input by -* returning an {@linkcode InputRequiredResult} instead of a final result. The -* helpers here build that return value and its embedded requests as NEUTRAL -* values; only the 2026-07-28 wire codec maps them to/from the wire. The -* 2025-era codec has no input-required vocabulary — on a 2025-era request the -* server's legacy shim (on by default) fulfils the embedded requests as real -* server→client requests and re-enters the handler, so the same return shape -* serves both eras; `ServerOptions.inputRequired.legacyShim: false` restores -* the pre-shim loud failure. -* -* There is no nominal brand: `resultType: 'input_required'` is the -* discriminator, and hand-built result literals are equally legal — the -* server seam re-checks the at-least-one rule for them. -*/ -function buildInputRequired(spec) { - const hasInputRequests = spec.inputRequests !== void 0 && Object.keys(spec.inputRequests).length > 0; - const hasRequestState = typeof spec.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new TypeError("inputRequired() requires at least one of inputRequests (with at least one entry) or requestState (spec: every InputRequiredResult MUST include at least one of the two)"); - return { - resultType: "input_required", - ...spec.inputRequests !== void 0 && { inputRequests: spec.inputRequests }, - ...spec.requestState !== void 0 && { requestState: spec.requestState } - }; -} -/** -* Builder for the input-required return value of multi-round-trip handlers, -* with per-kind constructors for the embedded requests -* (`inputRequired.elicit`, `inputRequired.elicitUrl`, -* `inputRequired.createMessage`, `inputRequired.listRoots`). -* -* @example Write-once tool requesting confirmation -* ```ts -* server.registerTool('deploy', { inputSchema: z.object({ env: z.string() }) }, async ({ env }, ctx) => { -* const confirmed = acceptedContent<{ confirm: boolean }>(ctx.mcpReq.inputResponses, 'confirm'); -* if (!confirmed) { -* return inputRequired({ -* inputRequests: { -* confirm: inputRequired.elicit({ -* message: `Deploy to ${env}?`, -* requestedSchema: { type: 'object', properties: { confirm: { type: 'boolean' } }, required: ['confirm'] } -* }) -* } -* }); -* } -* return { content: [{ type: 'text', text: `deployed to ${env}` }] }; -* }); -* ``` -*/ -const inputRequired = Object.assign(buildInputRequired, { - elicit(params) { - try { - return { - method: "elicitation/create", - params: normalizeElicitInputParams(params) - }; - } catch (error) { - throw error instanceof src_CX2iR2pK_ProtocolError ? new TypeError(error.message, { cause: error }) : error; - } - }, - elicitUrl(params) { - return { - method: "elicitation/create", - params: { - ...params, - mode: "url" - } - }; - }, - createMessage(params) { - return { - method: "sampling/createMessage", - params - }; - }, - listRoots() { - return { method: "roots/list" }; - } -}); -function acceptedContent(responses, key, schema) { - const view = inputResponse(responses, key); - if (view.kind !== "elicit" || view.action !== "accept" || view.content === void 0) return void 0; - if (schema === void 0) return view.content; - const outcome = schema["~standard"].validate(view.content); - if (outcome instanceof Promise) throw new TypeError("acceptedContent(responses, key, schema) requires a synchronously-validating schema"); - return outcome.issues === void 0 ? outcome.value : void 0; -} -/** -* Reads one entry of a retried request's `inputResponses` -* (`ctx.mcpReq.inputResponses`) as a discriminated view, covering -* decline/cancel detection and the non-elicitation response kinds that -* {@linkcode acceptedContent} does not surface. -* -* The values arrive from the client and are not re-validated here — treat -* them as untrusted input (validate elicitation content with the -* schema-aware {@linkcode acceptedContent} overload where it matters). -*/ -function inputResponse(responses, key) { - if (responses === void 0 || typeof responses !== "object" || responses === null) return { kind: "missing" }; - const entry = responses[key]; - if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return { kind: "missing" }; - const candidate = entry; - if (candidate["action"] === "accept" || candidate["action"] === "decline" || candidate["action"] === "cancel") { - const content = candidate["content"]; - return { - kind: "elicit", - action: candidate["action"], - ...content !== null && typeof content === "object" && !Array.isArray(content) && { content } - }; - } - if (Array.isArray(candidate["roots"])) return { - kind: "roots", - roots: candidate["roots"] - }; - if (typeof candidate["role"] === "string" && candidate["content"] !== void 0) return { - kind: "sampling", - result: candidate - }; - return { kind: "missing" }; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredDriver.ts -/** -* The multi-round-trip auto-fulfilment driver (protocol revision 2026-07-28). -* -* When a request to one of the multi-round-trip methods comes back as -* `input_required`, the driver fulfils the embedded input requests by -* dispatching them to the client's already-registered handlers (elicitation, -* sampling, roots — one generic engine, no per-feature API), then retries the -* original request with the collected `inputResponses` and a byte-exact echo -* of `requestState`, on a fresh request id, until the server returns a -* complete result or the round cap is exhausted. -* -* The driver is a LAYER OVER THE MANUAL PATH: each retry is issued with the -* same primitive a manual caller uses (`allowInputRequired` semantics — the -* retry hands back the next `input_required` payload instead of recursing), -* so the loop, the cap, and the pacing live in one place and disabling -* auto-fulfilment (`inputRequired.autoFulfill: false`) simply skips this -* module. Timeouts ride the EXISTING knobs: the per-leg `timeout` applies to -* every wire leg unchanged, and `maxTotalTimeout` bounds the whole flow by -* shrinking the budget passed to each leg — no new timer system. -*/ -/** -* Fixed pacing applied before retrying a requestState-only (load-shedding) -* leg — a leg that carries no embedded input requests, so nothing slows the -* loop down naturally. Counted in the same round cap. -*/ -const REQUEST_STATE_ONLY_LEG_PACING_MS = 250; -/** -* The message both multi-round-trip loops emit when the round cap is -* exhausted — the client driver as a typed error, the server-side legacy -* shim as its per-family failure. One formatter so the texts cannot drift -* (hosts and models read the tool-result copy verbatim). -*/ -function inputRequiredRoundsExceededMessage(method, maxRounds) { - return `Multi-round-trip request '${method}' still required input after ${maxRounds} rounds (inputRequired.maxRounds)`; -} -/** -* Abortable delay: resolves after `ms`, or rejects with the signal's reason -* (wrapped in an `SdkError` when it isn't already one) if the signal aborts -* first. Aborting after resolution is a no-op. Shared with the server-side -* legacy shim (the pacing semantics must match per era). -*/ -function sleep(ms, signal) { - return new Promise((resolve, reject) => { - if (signal?.aborted) { - reject(signal.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal.reason))); - return; - } - const timer = setTimeout(() => { - signal?.removeEventListener("abort", onAbort); - resolve(); - }, ms); - const onAbort = () => { - clearTimeout(timer); - reject(signal?.reason instanceof src_CX2iR2pK_SdkError ? signal.reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(signal?.reason))); - }; - signal?.addEventListener("abort", onAbort, { once: true }); - }); -} -/** -* A per-round abort linked to the caller's signal: the embedded sibling -* dispatches share it, so the first failure (or a caller abort) cancels the -* others instead of leaving them running. Shared with the server-side legacy -* shim (the abort-linkage semantics must match per era). -*/ -function linkedRoundAbort(outer) { - const controller = new AbortController(); - const onOuterAbort = () => controller.abort(outer?.reason); - outer?.addEventListener("abort", onOuterAbort, { once: true }); - if (outer?.aborted) controller.abort(outer.reason); - return { - signal: controller.signal, - abort: (reason) => controller.abort(reason), - dispose: () => outer?.removeEventListener("abort", onOuterAbort) - }; -} - -//#endregion -//#region ../core-internal/src/types/specTypeSchema.ts -/** -* Explicit allowlist of protocol Zod schemas that correspond to a public spec type in `types.ts`. -* -* This intentionally excludes internal helper schemas exported from `schemas.ts` that have no -* matching public type (e.g. `ListChangedOptionsBaseSchema`, `BaseRequestParamsSchema`, -* `NotificationsParamsSchema`, `ClientTasksCapabilitySchema`, `ServerTasksCapabilitySchema`). -* Keeping the list explicit means new public spec types must be added here deliberately, and -* internals never leak into `SpecTypeName`. -* -* `ResourceTemplateSchema` is included; its public type is exported as `ResourceTemplateType` -* (the bare name collides with the server package's `ResourceTemplate` class), so -* `SpecTypes['ResourceTemplate']` is structurally equal to `ResourceTemplateType` rather than to -* a type literally named `ResourceTemplate`. -*/ -const SPEC_SCHEMA_KEYS = [ - "AnnotationsSchema", - "AudioContentSchema", - "BaseMetadataSchema", - "BlobResourceContentsSchema", - "BooleanSchemaSchema", - "CallToolRequestSchema", - "CallToolRequestParamsSchema", - "CallToolResultSchema", - "CancelledNotificationSchema", - "CancelledNotificationParamsSchema", - "CancelTaskRequestSchema", - "CancelTaskResultSchema", - "ClientCapabilitiesSchema", - "ClientNotificationSchema", - "ClientRequestSchema", - "ClientResultSchema", - "CompatibilityCallToolResultSchema", - "CompleteRequestSchema", - "CompleteRequestParamsSchema", - "CompleteResultSchema", - "ContentBlockSchema", - "CreateMessageRequestSchema", - "CreateMessageRequestParamsSchema", - "CreateMessageResultSchema", - "CreateMessageResultWithToolsSchema", - "CreateTaskResultSchema", - "CursorSchema", - "DiscoverRequestSchema", - "DiscoverResultSchema", - "ElicitationCompleteNotificationSchema", - "ElicitationCompleteNotificationParamsSchema", - "ElicitRequestSchema", - "ElicitRequestFormParamsSchema", - "ElicitRequestParamsSchema", - "ElicitRequestURLParamsSchema", - "ElicitResultSchema", - "EmbeddedResourceSchema", - "EmptyResultSchema", - "EnumSchemaSchema", - "GetPromptRequestSchema", - "GetPromptRequestParamsSchema", - "GetPromptResultSchema", - "GetTaskPayloadRequestSchema", - "GetTaskPayloadResultSchema", - "GetTaskRequestSchema", - "GetTaskResultSchema", - "IconSchema", - "IconsSchema", - "ImageContentSchema", - "ImplementationSchema", - "InitializedNotificationSchema", - "InitializeRequestSchema", - "InitializeRequestParamsSchema", - "InitializeResultSchema", - "JSONArraySchema", - "JSONObjectSchema", - "JSONRPCErrorResponseSchema", - "JSONRPCMessageSchema", - "JSONRPCNotificationSchema", - "JSONRPCRequestSchema", - "JSONRPCResponseSchema", - "JSONRPCResultResponseSchema", - "JSONValueSchema", - "LegacyTitledEnumSchemaSchema", - "ListPromptsRequestSchema", - "ListPromptsResultSchema", - "ListResourcesRequestSchema", - "ListResourcesResultSchema", - "ListResourceTemplatesRequestSchema", - "ListResourceTemplatesResultSchema", - "ListRootsRequestSchema", - "ListRootsResultSchema", - "ListTasksRequestSchema", - "ListTasksResultSchema", - "ListToolsRequestSchema", - "ListToolsResultSchema", - "LoggingLevelSchema", - "LoggingMessageNotificationSchema", - "LoggingMessageNotificationParamsSchema", - "ModelHintSchema", - "ModelPreferencesSchema", - "MultiSelectEnumSchemaSchema", - "NotificationSchema", - "NumberSchemaSchema", - "PaginatedRequestSchema", - "PaginatedRequestParamsSchema", - "PaginatedResultSchema", - "PingRequestSchema", - "PrimitiveSchemaDefinitionSchema", - "ProgressSchema", - "ProgressNotificationSchema", - "ProgressNotificationParamsSchema", - "ProgressTokenSchema", - "PromptSchema", - "PromptArgumentSchema", - "PromptListChangedNotificationSchema", - "PromptMessageSchema", - "PromptReferenceSchema", - "ReadResourceRequestSchema", - "ReadResourceRequestParamsSchema", - "ReadResourceResultSchema", - "RelatedTaskMetadataSchema", - "RequestSchema", - "RequestIdSchema", - "RequestMetaSchema", - "ResourceSchema", - "ResourceContentsSchema", - "ResourceLinkSchema", - "ResourceListChangedNotificationSchema", - "ResourceRequestParamsSchema", - "ResourceTemplateSchema", - "ResourceTemplateReferenceSchema", - "ResourceUpdatedNotificationSchema", - "ResourceUpdatedNotificationParamsSchema", - "ResultMetaObjectSchema", - "ResultSchema", - "RoleSchema", - "RootSchema", - "RootsListChangedNotificationSchema", - "SamplingContentSchema", - "SamplingMessageSchema", - "SamplingMessageContentBlockSchema", - "ServerCapabilitiesSchema", - "ServerNotificationSchema", - "ServerRequestSchema", - "ServerResultSchema", - "SetLevelRequestSchema", - "SetLevelRequestParamsSchema", - "SingleSelectEnumSchemaSchema", - "StringSchemaSchema", - "SubscribeRequestSchema", - "SubscribeRequestParamsSchema", - "SubscriptionFilterSchema", - "SubscriptionsAcknowledgedNotificationSchema", - "SubscriptionsAcknowledgedNotificationParamsSchema", - "SubscriptionsListenRequestSchema", - "SubscriptionsListenRequestParamsSchema", - "SubscriptionsListenResultSchema", - "SubscriptionsListenResultMetaSchema", - "TaskAugmentedRequestParamsSchema", - "TaskCreationParamsSchema", - "TaskMetadataSchema", - "TaskSchema", - "TaskStatusSchema", - "TaskStatusNotificationSchema", - "TaskStatusNotificationParamsSchema", - "TextContentSchema", - "TextResourceContentsSchema", - "TitledMultiSelectEnumSchemaSchema", - "TitledSingleSelectEnumSchemaSchema", - "ToolSchema", - "ToolAnnotationsSchema", - "ToolChoiceSchema", - "ToolExecutionSchema", - "ToolListChangedNotificationSchema", - "ToolResultContentSchema", - "ToolUseContentSchema", - "UnsubscribeRequestSchema", - "UnsubscribeRequestParamsSchema", - "UntitledMultiSelectEnumSchemaSchema", - "UntitledSingleSelectEnumSchemaSchema" -]; -const authSchemas = { - IdJagTokenExchangeResponseSchema: IdJagTokenExchangeResponseSchema, - OAuthClientInformationFullSchema: OAuthClientInformationFullSchema, - OAuthClientInformationSchema: OAuthClientInformationSchema, - OAuthClientMetadataSchema: OAuthClientMetadataSchema, - OAuthClientRegistrationErrorSchema: OAuthClientRegistrationErrorSchema, - OAuthErrorResponseSchema: OAuthErrorResponseSchema, - OAuthMetadataSchema: OAuthMetadataSchema, - OAuthProtectedResourceMetadataSchema: OAuthProtectedResourceMetadataSchema, - OAuthTokenRevocationRequestSchema: OAuthTokenRevocationRequestSchema, - OAuthTokensSchema: OAuthTokensSchema, - OpenIdProviderDiscoveryMetadataSchema: OpenIdProviderDiscoveryMetadataSchema, - OpenIdProviderMetadataSchema: OpenIdProviderMetadataSchema -}; -const _specTypeSchemas = {}; -const _isSpecType = {}; -function register(key, schema) { - const name = key.slice(0, -6); - _specTypeSchemas[name] = schema; - _isSpecType[name] = (v) => schema.safeParse(v).success; -} -for (const key of SPEC_SCHEMA_KEYS) register(key, schemas_exports[key]); -for (const [key, schema] of Object.entries(authSchemas)) register(key, schema); -/** -* Runtime validators for every MCP spec type, keyed by type name. -* -* Use this when you need to validate a spec-defined shape at a boundary the SDK does not own, for -* example an extension's custom-method payload that embeds a `CallToolResult`, or a value read from -* storage that should be a `Tool`. -* -* Each entry implements the Standard Schema interface, so it composes with any -* Standard-Schema-aware library. For a simple boolean check, use {@linkcode isSpecType} instead. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#specTypeSchemas_basicUsage" -* const result = specTypeSchemas.CallToolResult['~standard'].validate(untrusted); -* if (result.issues === undefined) { -* // result.value is CallToolResult -* } -* ``` -*/ -const specTypeSchemas = Object.freeze(_specTypeSchemas); -/** -* Type predicates for every MCP spec type, keyed by type name. -* -* Returns `true` if the value satisfies the schema's input type (`z.input<>`, before defaults and -* transforms are applied), and narrows to that input type. For schemas with `.default()` or -* `.preprocess()`, this may accept values that do not structurally match the named output type; -* for example `isSpecType.CallToolResult({})` is `true` because `content` has a default. Use -* `specTypeSchemas.X['~standard'].validate(value)` when you need the validated output value. -* -* Each guard is a standalone function, so it can be passed directly as a callback. -* -* @example -* ```ts source="./specTypeSchema.examples.ts#isSpecType_basicUsage" -* if (isSpecType.ContentBlock(value)) { -* // value is ContentBlock -* } -* -* const blocks = mixed.filter(isSpecType.ContentBlock); -* ``` -*/ -const isSpecType = Object.freeze(_isSpecType); - -//#endregion -//#region ../core-internal/src/wire/bootstrap.ts -function bootstrapOutboundCodec(method) { - switch (method) { - case "initialize": - case "notifications/initialized": return src_CX2iR2pK_codecForVersion(void 0); - case "server/discover": return src_CX2iR2pK_codecForVersion(src_CX2iR2pK_MODERN_WIRE_REVISION); - default: return; - } -} - -//#endregion -//#region ../core-internal/src/shared/protocol.ts -/** -* The default request timeout, in milliseconds. -*/ -const DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4; -/** -* The reserved per-request `_meta` envelope keys (protocol revision -* 2026-07-28). The protocol layer lifts these out of inbound `_meta` before -* handlers run and surfaces them at `ctx.mcpReq.envelope` — they are -* wire-level bookkeeping, not handler material. -*/ -const RESERVED_ENVELOPE_META_KEYS = [ - auth_CUe6YdwF_PROTOCOL_VERSION_META_KEY, - auth_CUe6YdwF_CLIENT_INFO_META_KEY, - auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY, - LOG_LEVEL_META_KEY -]; -/** -* Top-level params members carrying multi-round-trip driver material -* (protocol revision 2026-07-28). The spec reserves these names on -* client-initiated REQUESTS only — notification params keep them untouched -* (a vendor notification may legitimately use the same names). -*/ -const RETRY_PARAMS_KEYS = ["inputResponses", "requestState"]; -/** -* Lift wire-only material out of an inbound message so handlers see exactly -* the 2025-era shape, and surface it for the protocol layer (requests: via -* `ctx.mcpReq`). What counts as wire-only depends on the message kind: the -* reserved envelope `_meta` keys are reserved on every message, while the -* multi-round-trip retry fields (`inputResponses`/`requestState`) are -* reserved on client-initiated requests only — so notifications get only the -* envelope lift, and their top-level params stay untouched. Messages without -* wire-only material are returned unchanged (same reference). -*/ -function liftWireOnlyMaterial(message, kind) { - const params = message.params; - if (!isPlainObject$1(params)) return { - message, - lifted: {} - }; - const meta = params._meta; - const envelopeKeys = isPlainObject$1(meta) ? RESERVED_ENVELOPE_META_KEYS.filter((key) => key in meta) : []; - const retryKeys = kind === "request" ? RETRY_PARAMS_KEYS.filter((key) => key in params) : []; - if (envelopeKeys.length === 0 && retryKeys.length === 0) return { - message, - lifted: {} - }; - const lifted = {}; - const nextParams = { ...params }; - if (envelopeKeys.length > 0 && isPlainObject$1(meta)) { - const envelope = {}; - const nextMeta = { ...meta }; - for (const key of envelopeKeys) { - envelope[key] = meta[key]; - delete nextMeta[key]; - } - lifted.envelope = envelope; - if (Object.keys(nextMeta).length > 0) nextParams._meta = nextMeta; - else delete nextParams._meta; - } - for (const key of retryKeys) { - if (key === "inputResponses") lifted.inputResponses = nextParams[key]; - if (key === "requestState") lifted.requestState = nextParams[key]; - delete nextParams[key]; - } - return { - message: { - ...message, - params: nextParams - }, - lifted - }; -} -/** -* Standard Schema adapter over the era codec's `validateResult` function (the -* function-only WireCodec contract exposes no schema objects). Used by the -* spec-method `request()` overload so the request funnel keeps a single -* `StandardSchemaV1`-shaped validation seam for both spec and explicit-schema -* paths. -* -* Returns `undefined` when the method has no result entry on this era's -* registry — the caller maps that to the synchronous "pass a result schema" -* TypeError, exactly matching the pre-function-only behavior the -* typedMapAlignment suite pins (the result map deliberately excludes the -* `tasks/*` methods, so the spec-method overload refuses them up front). -*/ -function codecResultValidator(codec, method) { - const probe = codec.validateResult(method, void 0); - if (!probe.ok && probe.reason === "not-in-era") return void 0; - return { "~standard": { - version: 1, - vendor: "mcp-wire-codec", - validate(value) { - const outcome = codec.validateResult(method, value); - if (outcome.ok) return { value: outcome.value }; - return { issues: [{ message: outcome.reason === "invalid" ? outcome.message : `not-in-era: ${method}` }] }; - } - } }; -} -/** -* Builds the `ctx.mcpReq.requestState` accessor for a resolved value. The -* `as T` below is the one place {@linkcode RequestStateAccessor}'s -* caller-asserted typing is implemented — no implementation can produce an -* arbitrary `T` from a runtime value honestly. -*/ -function requestStateAccessor(value) { - return () => value; -} -/** Shared no-state accessor: the common case allocates nothing per request. */ -const NO_REQUEST_STATE = requestStateAccessor(void 0); -/** -* Returns a context whose `requestState` accessor reads the given value — -* how the server seam hands a verify hook's decoded payload (or the legacy -* shim's per-round echo) to the handler without mutating the original -* context. -*/ -function withRequestStateValue(ctx, value) { - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - requestState: requestStateAccessor(value) - } - }; -} -let writeNegotiatedProtocolVersion; -/** -* Package-internal write channel for a {@linkcode Protocol} instance's -* negotiated protocol version, for callers outside the class hierarchy: -* tests and the (future) modern-era server entry that marks a factory -* instance modern at binding time. Exported on the core internal barrel -* only — never public API. -*/ -function src_CX2iR2pK_setNegotiatedProtocolVersion(instance, version) { - writeNegotiatedProtocolVersion(instance, version); -} -/** -* Implements MCP protocol framing on top of a pluggable transport, including -* features like request/response linking, notifications, and progress. -* -* `Protocol` is abstract; `Client` and `Server` are the concrete role-specific -* implementations most code should use. -*/ -var Protocol = class { - _transport; - _requestMessageId = 0; - _requestHandlers = /* @__PURE__ */ new Map(); - _requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - _notificationHandlers = /* @__PURE__ */ new Map(); - _responseHandlers = /* @__PURE__ */ new Map(); - _progressHandlers = /* @__PURE__ */ new Map(); - _timeoutInfo = /* @__PURE__ */ new Map(); - _pendingDebouncedNotifications = /* @__PURE__ */ new Set(); - /** - * The protocol version negotiated for the current connection (`undefined` - * before negotiation completes), which determines the wire era this - * instance speaks. Set by the SDK's negotiation and initialize paths - * (`Client.connect`, `Server._oninitialize`). - */ - _negotiatedProtocolVersion; - static { - writeNegotiatedProtocolVersion = (instance, version) => { - instance._negotiatedProtocolVersion = version; - }; - } - _supportedProtocolVersions; - /** - * Callback for when the connection is closed for any reason. - * - * This is invoked when {@linkcode Protocol.close | close()} is called as well. - */ - onclose; - /** - * Callback for when an error occurs. - * - * Note that errors are not necessarily fatal; they are used for reporting any kind of exceptional condition out of band. - */ - onerror; - /** - * A handler to invoke for any request types that do not have their own handler installed. - */ - fallbackRequestHandler; - /** - * A handler to invoke for any notification types that do not have their own handler installed. - */ - fallbackNotificationHandler; - constructor(_options) { - this._options = _options; - this._supportedProtocolVersions = _options?.supportedProtocolVersions ?? auth_CUe6YdwF_SUPPORTED_PROTOCOL_VERSIONS; - this.setNotificationHandler("notifications/cancelled", (notification) => { - this._oncancel(notification); - }); - this.setNotificationHandler("notifications/progress", (notification) => { - this._onprogress(notification); - }); - this.setRequestHandler("ping", (_request) => ({})); - } - /** - * Drop consult for inbound messages whose transport did not classify them - * at the edge — long-lived channels such as stdio, where a role class may - * need to decline traffic the negotiated era has no answer for (the - * client-side inbound-request drop on modern-era connections: the - * 2026-07-28 era has no server→client request channel, and on stdio the - * client must never write JSON-RPC responses). - * - * Consulted ONLY when the transport supplied no - * {@linkcode MessageExtraInfo.classification}: edge-classified traffic - * never reaches the hook. Returning `'drop'` discards the message without - * writing any response (requests are surfaced via `onerror`). The base - * implementation returns `undefined`: unclassified traffic keeps today's - * dispatch path unchanged. Era selection never happens here — era is - * instance state, owned by the serving entry that constructed and - * connected the instance. - */ - _shouldDropInbound(_message) {} - /** - * The per-request `_meta` envelope this instance attaches to every outgoing - * request and notification, when one applies. The base implementation - * returns `undefined` (no envelope — the 2025-era posture, so legacy-era - * outbound traffic is byte-identical to a build without this seam). - * `Client` overrides it on a connection that negotiated a modern (2026-07-28+) - * era to return the reserved protocol-version / client-info / - * client-capabilities keys. User-supplied `_meta` keys take precedence over - * the auto-attached ones. - */ - _outboundMetaEnvelope() {} - /** - * Attach this instance's outbound `_meta` envelope (when one is configured) - * to a request or notification. A no-op when the seam returns `undefined` - * — the message returns by reference, so the legacy-era wire stays - * byte-identical. User-supplied `_meta` keys are spread last so they win - * over the auto-attached envelope keys. - */ - _envelopeOutbound(message) { - const envelope = this._outboundMetaEnvelope(); - if (envelope === void 0) return message; - const params = message.params ?? {}; - return { - ...message, - params: { - ...params, - _meta: { - ...envelope, - ...params._meta - } - } - }; - } - /** - * Extension point for non-`complete` decoded results in the response - * funnel: a result the wire codec discriminated into a kind other than - * `'complete'` or `'invalid'` is handed here for the role class to - * resolve. The base default surfaces it as a typed - * {@linkcode SdkErrorCode.UnsupportedResultType} error (no retry). - * - * Intended consumers (named so the seam stays accountable): - * - the `Client`'s multi-round-trip auto-fulfilment engine, which fulfils - * `'input_required'` results through the registered - * elicitation/sampling/roots handlers and retries via `flow.retry`; - * - a future client-side terminal-result handler for - * `subscriptions/listen`, when the spec defines one. - * - * `Server` instances never receive `input_required` responses on their - * outbound legs and leave the base behavior in place. - */ - _resolveNonCompleteResult(decoded, flow) { - return Promise.reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.UnsupportedResultType, `Unsupported result type '${decoded.kind}' for ${flow.request.method}`, { - resultType: decoded.kind, - method: flow.request.method - })); - } - /** - * Protected accessor for a registered request handler. Used by role - * classes that dispatch synthesized requests through the same stored - * handler chain (e.g. the `Client` fulfilling an embedded multi-round-trip - * input request). - */ - _getRequestHandler(method) { - return this._requestHandlers.get(method); - } - async _oncancel(notification) { - if (!notification.params.requestId) return; - this._requestHandlerAbortControllers.get(notification.params.requestId)?.abort(notification.params.reason); - } - _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) { - this._timeoutInfo.set(messageId, { - timeoutId: setTimeout(onTimeout, timeout), - startTime: Date.now(), - timeout, - maxTotalTimeout, - resetTimeoutOnProgress, - onTimeout - }); - } - _resetTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (!info) return false; - const totalElapsed = Date.now() - info.startTime; - if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) { - this._timeoutInfo.delete(messageId); - throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Maximum total timeout exceeded", { - maxTotalTimeout: info.maxTotalTimeout, - totalElapsed - }); - } - clearTimeout(info.timeoutId); - info.timeoutId = setTimeout(info.onTimeout, info.timeout); - return true; - } - _cleanupTimeout(messageId) { - const info = this._timeoutInfo.get(messageId); - if (info) { - clearTimeout(info.timeoutId); - this._timeoutInfo.delete(messageId); - } - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The caller assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - */ - async connect(transport) { - this._transport = transport; - const _onclose = this.transport?.onclose; - this._transport.onclose = () => { - try { - _onclose?.(); - } finally { - this._onclose(); - } - }; - const _onerror = this.transport?.onerror; - this._transport.onerror = (error) => { - _onerror?.(error); - this._onerror(error); - }; - const _onmessage = this._transport?.onmessage; - this._transport.onmessage = (message, extra) => { - _onmessage?.(message, extra); - if (src_CX2iR2pK_isJSONRPCResultResponse(message) || src_CX2iR2pK_isJSONRPCErrorResponse(message)) this._onresponse(message); - else if (src_CX2iR2pK_isJSONRPCRequest(message)) this._onrequest(message, extra); - else if (src_CX2iR2pK_isJSONRPCNotification(message)) this._onnotification(message, extra); - else this._onerror(/* @__PURE__ */ new Error(`Unknown message type: ${JSON.stringify(message)}`)); - }; - transport.setSupportedProtocolVersions?.(this._supportedProtocolVersions); - await this._transport.start(); - } - /** - * Transport-close hook. Subclass overrides MUST call `super._onclose()` - * after their own cleanup — base teardown (response-handler settlement, - * timeout clearing, in-flight request abort) does not run otherwise. - */ - _onclose() { - const responseHandlers = this._responseHandlers; - this._responseHandlers = /* @__PURE__ */ new Map(); - this._progressHandlers.clear(); - this._pendingDebouncedNotifications.clear(); - for (const info of this._timeoutInfo.values()) clearTimeout(info.timeoutId); - this._timeoutInfo.clear(); - const requestHandlerAbortControllers = this._requestHandlerAbortControllers; - this._requestHandlerAbortControllers = /* @__PURE__ */ new Map(); - const error = new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.ConnectionClosed, "Connection closed"); - this._transport = void 0; - try { - this.onclose?.(); - } finally { - for (const handler of responseHandlers.values()) handler(error); - for (const controller of requestHandlerAbortControllers.values()) controller.abort(error); - } - } - _onerror(error) { - this.onerror?.(error); - } - /** - * Inbound-notification dispatch. Subclass overrides MUST delegate - * unmatched traffic to `super._onnotification(rawNotification, extra)` — - * an override that consumes only what it owns and falls through to base - * dispatch for everything else. - */ - _onnotification(rawNotification, extra) { - const { message: notification } = liftWireOnlyMaterial(rawNotification, "notification"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawNotification) === "drop") return; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound notification '${notification.method}': classified as ${classified} but this instance serves ${codec.era}`)); - return; - } - } - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) return; - const handler = this._notificationHandlers.get(notification.method); - const fallback = this.fallbackNotificationHandler; - if (handler === void 0 && fallback === void 0) return; - Promise.resolve().then(() => handler === void 0 ? fallback(notification) : handler(notification, codec)).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Uncaught error in notification handler: ${error}`))); - } - _onrequest(rawRequest, extra) { - const { message: request, lifted } = liftWireOnlyMaterial(rawRequest, "request"); - const codec = this._negotiatedWireCodec(); - if (extra?.classification === void 0 && this._shouldDropInbound(rawRequest) === "drop") { - this._onerror(/* @__PURE__ */ new Error(`Dropped inbound request '${rawRequest.method}': not servable on this connection's protocol era`)); - return; - } - const capturedTransport = this._transport; - const sendErrorResponse = (code, message, data) => { - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }; - capturedTransport?.send(errorResponse).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send an error response: ${error}`))); - }; - if (extra?.classification !== void 0) { - const classified = classifiedWireEra(extra.classification); - if (classified !== codec.era) { - this._onerror(/* @__PURE__ */ new Error(`Era mismatch on inbound request '${request.method}': classified as ${classified} but this instance serves ${codec.era}`)); - const requested = extra.classification.revision ?? classified; - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.UnsupportedProtocolVersion, `Unsupported protocol version: ${requested}`, { - supported: this._supportedProtocolVersions, - requested - }); - return; - } - } - if (isSpecRequestMethod(request.method) && !codec.hasRequestMethod(request.method)) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const handler = this._requestHandlers.get(request.method) ?? this.fallbackRequestHandler; - if (handler === void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.MethodNotFound, "Method not found"); - return; - } - const envelopeError = codec.checkInboundEnvelope(lifted); - if (envelopeError !== void 0) { - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, envelopeError); - return; - } - const sendNotification = (notification, options) => this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, { - ...options, - relatedRequestId: request.id - }); - const sendRequest = (r, resultSchema, options) => this._requestWithSchemaViaCodec(this._resolveOutboundCodec(r.method), r, resultSchema, { - ...options, - relatedRequestId: request.id - }); - const abortController = new AbortController(); - this._requestHandlerAbortControllers.set(request.id, abortController); - const partitionedInputResponses = lifted.inputResponses === void 0 ? void 0 : partitionInputResponses(lifted.inputResponses); - const baseCtx = { - sessionId: capturedTransport?.sessionId, - mcpReq: { - id: request.id, - method: request.method, - _meta: request.params?._meta, - ...lifted.envelope !== void 0 && { envelope: lifted.envelope }, - ...partitionedInputResponses !== void 0 && { inputResponses: partitionedInputResponses.accepted }, - ...partitionedInputResponses !== void 0 && partitionedInputResponses.droppedKeys.length > 0 && { droppedInputResponseKeys: partitionedInputResponses.droppedKeys }, - requestState: lifted.requestState === void 0 ? NO_REQUEST_STATE : requestStateAccessor(lifted.requestState), - signal: abortController.signal, - send: ((r, schemaOrOptions, maybeOptions) => { - const sendCodec = this._resolveOutboundCodec(r.method); - this._assertOutboundRequestInEra(sendCodec, r.method); - if (isStandardSchema(schemaOrOptions)) return sendRequest(r, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(sendCodec, r.method); - if (validate === void 0) throw new TypeError(`'${r.method}' is not a spec method; pass a result schema as the second argument to ctx.mcpReq.send().`); - return sendRequest(r, validate, schemaOrOptions); - }), - notify: sendNotification - }, - http: extra?.authInfo ? { authInfo: extra.authInfo } : void 0 - }; - const ctx = this.buildContext(baseCtx, extra); - Promise.resolve().then(() => handler(request, ctx)).then(async (result) => { - if (abortController.signal.aborted) return; - let encoded; - try { - encoded = codec.encodeResult(request.method, result, this._outboundServerInfo()); - } catch (error) { - this._onerror(/* @__PURE__ */ new Error(`Failed to encode result for ${request.method}: ${error}`)); - sendErrorResponse(src_CX2iR2pK_ProtocolErrorCode.InternalError, "Internal error"); - return; - } - const response = { - result: encoded, - jsonrpc: "2.0", - id: request.id - }; - await capturedTransport?.send(response); - }, async (error) => { - if (abortController.signal.aborted) return; - const thrownCode = Number.isSafeInteger(error["code"]) ? error["code"] : src_CX2iR2pK_ProtocolErrorCode.InternalError; - const errorResponse = { - jsonrpc: "2.0", - id: request.id, - error: { - code: codec.encodeErrorCode(thrownCode), - message: error.message ?? "Internal error", - ...error["data"] !== void 0 && { data: error["data"] } - } - }; - await capturedTransport?.send(errorResponse); - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send response: ${error}`))).finally(() => { - if (this._requestHandlerAbortControllers.get(request.id) === abortController) this._requestHandlerAbortControllers.delete(request.id); - }); - } - _onprogress(notification) { - const { progressToken, ...params } = notification.params; - const messageId = Number(progressToken); - const handler = this._progressHandlers.get(messageId); - if (!handler) { - this._onerror(/* @__PURE__ */ new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`)); - return; - } - const responseHandler = this._responseHandlers.get(messageId); - const timeoutInfo = this._timeoutInfo.get(messageId); - if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try { - this._resetTimeout(messageId); - } catch (error) { - this._responseHandlers.delete(messageId); - this._progressHandlers.delete(messageId); - this._cleanupTimeout(messageId); - responseHandler(error); - return; - } - handler(params); - } - /** - * Inbound-response dispatch. Subclass overrides MUST delegate unmatched - * traffic to `super._onresponse(response)` — an override that consumes - * only what it owns and falls through to base dispatch for everything - * else. - */ - _onresponse(response) { - const messageId = Number(response.id); - const handler = this._responseHandlers.get(messageId); - if (handler === void 0) { - this._onerror(/* @__PURE__ */ new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`)); - return; - } - this._responseHandlers.delete(messageId); - this._cleanupTimeout(messageId); - this._progressHandlers.delete(messageId); - if (src_CX2iR2pK_isJSONRPCResultResponse(response)) handler(response); - else handler(src_CX2iR2pK_ProtocolError.fromError(response.error.code, response.error.message, response.error.data)); - } - get transport() { - return this._transport; - } - /** - * Closes the connection. - */ - async close() { - await this._transport?.close(); - } - request(request, schemaOrOptions, maybeOptions) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - if (isStandardSchema(schemaOrOptions)) return this._requestWithSchemaViaCodec(codec, request, schemaOrOptions, maybeOptions); - const validate = codecResultValidator(codec, request.method); - if (validate === void 0) throw new TypeError(`'${request.method}' is not a spec method; pass a result schema as the second argument to request().`); - return this._requestWithSchemaViaCodec(codec, request, validate, schemaOrOptions); - } - /** - * The wire codec for this instance's negotiated era — the phase-2 truth: - * everything an established connection sends and receives resolves - * through it. Legacy until a version has been negotiated. - */ - _negotiatedWireCodec() { - return src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - } - /** - * Protected accessor for the instance's negotiated wire codec, for role - * classes (Client/Server/McpServer) routing era-dependent behavior - * through the codec's function-only surface — `samplingResultVariant`, - * `outboundEnvelope`, `projectCallToolResult` — instead of branching on - * the protocol version themselves. - */ - _wireCodec() { - return this._negotiatedWireCodec(); - } - /** - * Outbound codec resolution: while the negotiated version is still unset - * (the negotiation window), lifecycle messages are bootstrap-pinned BY - * METHOD — they self-identify their era (`initialize` IS the legacy - * handshake, `server/discover` IS the modern probe). Once a version has - * been negotiated, the instance era is authoritative for everything — a - * negotiated session never re-routes a method onto the other era. - */ - _resolveOutboundCodec(method) { - if (this._negotiatedProtocolVersion === void 0) { - const pinned = bootstrapOutboundCodec(method); - if (pinned) return pinned; - } - return this._negotiatedWireCodec(); - } - /** - * Era gate for outbound requests — deletions are physical in BOTH - * directions: sending a spec method that the resolved era does not define - * dies locally with a typed error before anything reaches the transport. - * Methods outside the spec universe are consumer-owned extension methods - * and stay era-blind. - */ - _assertOutboundRequestInEra(codec, method) { - if (isSpecRequestMethod(method) && !codec.hasRequestMethod(method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Method '${method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method, - era: codec.era - }); - } - /** - * Sends a request and waits for a response, using the provided schema for - * validation instead of the era registry's method-keyed entry. - * - * This is the internal implementation used by SDK methods whose result - * schema cannot be expressed as a method-keyed registry entry — the one - * surviving case is `server.createMessage`, whose result schema depends - * on the REQUEST params (tools vs no tools) — and by callers passing - * explicit compatibility schemas. Spec methods are still era-gated here: - * an explicit schema never smuggles a deleted method onto the wire. - */ - _requestWithSchema(request, resultSchema, options) { - const codec = this._resolveOutboundCodec(request.method); - this._assertOutboundRequestInEra(codec, request.method); - return this._requestWithSchemaViaCodec(codec, request, resultSchema, options); - } - /** - * The request funnel proper, keyed by the resolved era codec: the codec - * owns result decoding (raw-first `resultType` discrimination — V-1 — - * and the era's lift posture) before the schema validation step. - */ - _requestWithSchemaViaCodec(codec, request, resultSchema, options) { - const { relatedRequestId, resumptionToken, onresumptiontoken, headers } = options ?? {}; - const flowStartedAt = Date.now(); - let onAbort; - let cleanupMessageId; - return new Promise((resolve, reject) => { - const earlyReject = (error) => { - reject(error); - }; - if (!this._transport) { - earlyReject(/* @__PURE__ */ new Error("Not connected")); - return; - } - if (this._options?.enforceStrictCapabilities === true) try { - this.assertCapabilityForMethod(request.method); - } catch (error) { - earlyReject(error); - return; - } - if (options?.signal?.aborted) { - const reason = options.signal.reason; - throw reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason)); - } - const requestAbort = codec.era === src_CX2iR2pK_MODERN_WIRE_REVISION && this._transport.hasPerRequestStream === true ? new AbortController() : void 0; - const messageId = this._requestMessageId++; - cleanupMessageId = messageId; - const jsonrpcRequest = { - ...request, - jsonrpc: "2.0", - id: messageId - }; - if (options?.onprogress) { - this._progressHandlers.set(messageId, options.onprogress); - jsonrpcRequest.params = { - ...request.params, - _meta: { - ...request.params?._meta, - progressToken: messageId - } - }; - } - const outbound = this._envelopeOutbound(jsonrpcRequest); - let responseReceived = false; - const cancel = (reason) => { - if (responseReceived) return; - this._progressHandlers.delete(messageId); - if (requestAbort === void 0) this._transport?.send(this._envelopeOutbound({ - jsonrpc: "2.0", - method: "notifications/cancelled", - params: { - requestId: messageId, - reason: String(reason) - } - }), { - relatedRequestId, - resumptionToken, - onresumptiontoken - }).catch((error) => this._onerror(/* @__PURE__ */ new Error(`Failed to send cancellation: ${error}`))); - else requestAbort.abort(); - reject(reason instanceof src_CX2iR2pK_SdkError ? reason : new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, String(reason))); - }; - this._responseHandlers.set(messageId, (response) => { - if (options?.signal?.aborted) return; - responseReceived = true; - if (response instanceof Error) return reject(response); - let decoded; - try { - decoded = codec.decodeResult(request.method, response.result); - } catch (error) { - return reject(error instanceof Error ? error : new Error(String(error))); - } - if (decoded.kind === "invalid") return reject(decoded.error); - if (decoded.kind === "input_required") { - if (options?.allowInputRequired === true) return resolve(manualInputRequiredValue(decoded)); - const flow = { - codec, - request, - resultSchema, - options, - flowStartedAt, - retry: (params, legOptions) => this._requestWithSchemaViaCodec(codec, params === void 0 ? { method: request.method } : { - method: request.method, - params - }, resultSchema, legOptions) - }; - return resolve(this._resolveNonCompleteResult(decoded, flow)); - } - const result = decoded.result; - validateStandardSchema(resultSchema, result).then((parseResult) => { - if (parseResult.success) resolve(parseResult.data); - else reject(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid result for ${request.method}: ${parseResult.error}`)); - }, reject); - }); - onAbort = () => cancel(options?.signal?.reason); - options?.signal?.addEventListener("abort", onAbort, { once: true }); - const timeout = options?.timeout ?? DEFAULT_REQUEST_TIMEOUT_MSEC; - const timeoutHandler = () => cancel(new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.RequestTimeout, "Request timed out", { timeout })); - this._setupTimeout(messageId, timeout, options?.maxTotalTimeout, timeoutHandler, options?.resetTimeoutOnProgress ?? false); - this._transport.send(outbound, { - relatedRequestId, - resumptionToken, - onresumptiontoken, - headers, - requestSignal: requestAbort?.signal - }).catch((error) => { - this._progressHandlers.delete(messageId); - reject(error); - }); - }).finally(() => { - if (onAbort) options?.signal?.removeEventListener("abort", onAbort); - if (cleanupMessageId !== void 0) { - this._responseHandlers.delete(cleanupMessageId); - this._cleanupTimeout(cleanupMessageId); - } - }); - } - /** - * Emits a notification, which is a one-way message that does not expect a response. - */ - async notification(notification, options) { - return this._notificationViaCodec(this._resolveOutboundCodec(notification.method), notification, options); - } - /** - * The notification funnel proper, keyed by the resolved era codec — - * direct sends and related notifications (`ctx.mcpReq.notify`) alike - * resolve through the instance's negotiated era at send time. - */ - async _notificationViaCodec(codec, notification, options) { - if (!this._transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (isSpecNotificationMethod(notification.method) && !codec.hasNotificationMethod(notification.method)) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Notification '${notification.method}' is not supported by the negotiated protocol version (wire era ${codec.era})`, { - method: notification.method, - era: codec.era - }); - this.assertNotificationCapability(notification.method); - const jsonrpcNotification = this._envelopeOutbound({ - jsonrpc: "2.0", - ...notification - }); - if ((this._options?.debouncedNotificationMethods ?? []).includes(notification.method) && !notification.params && !options?.relatedRequestId) { - if (this._pendingDebouncedNotifications.has(notification.method)) return; - this._pendingDebouncedNotifications.add(notification.method); - Promise.resolve().then(() => { - this._pendingDebouncedNotifications.delete(notification.method); - if (!this._transport) return; - this._transport?.send(jsonrpcNotification, options).catch((error) => this._onerror(error)); - }); - return; - } - await this._transport.send(jsonrpcNotification, options); - } - setRequestHandler(method, schemasOrHandler, maybeHandler) { - this.assertRequestHandlerCapability(method); - let stored; - if (typeof schemasOrHandler === "function") { - if (!isSpecRequestMethod(method)) throw new TypeError(`'${method}' is not a spec request method; pass schemas as the second argument to setRequestHandler().`); - stored = (request, ctx) => { - const dispatchCodec = this._negotiatedWireCodec(); - let outcome = dispatchCodec.validateRequest(method, request); - if (!outcome.ok && outcome.reason === "not-in-era") outcome = dispatchCodec.validateInputRequest(method, request); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value, ctx)); - }; - } else if (maybeHandler) stored = async (request, ctx) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...request.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for ${method}: ${parsed.error}`); - return maybeHandler(parsed.data, ctx); - }; - else throw new TypeError("setRequestHandler: handler is required"); - this._requestHandlers.set(method, this._wrapHandler(method, stored)); - } - /** - * Hook for subclasses to wrap a registered request handler with role-specific - * validation or behavior (e.g. `Server` validates `tools/call` results, `Client` - * validates `elicitation/create` mode and result). Runs for both the 2-arg and - * 3-arg registration paths. The default implementation is identity. - * - * Subclasses overriding this hook avoid redeclaring `setRequestHandler`'s overload set. - */ - _wrapHandler(_method, handler) { - return handler; - } - /** - * Hook for subclasses to supply the implementation identity the 2026-era - * encode seam stamps into outbound result `_meta` under - * `io.modelcontextprotocol/serverInfo` (spec PR #3002: servers SHOULD - * identify themselves on every response). The default is `undefined` — no - * stamp. Only `Server` overrides this: the key identifies the software - * producing a response, and the 2025-era codec never stamps anything - * regardless (the never-stamp guarantee). - */ - _outboundServerInfo() {} - /** - * Removes the request handler for the given method. - */ - removeRequestHandler(method) { - this._requestHandlers.delete(method); - } - /** - * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed. - */ - assertCanSetRequestHandler(method) { - if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`); - } - setNotificationHandler(method, schemasOrHandler, maybeHandler) { - if (typeof schemasOrHandler === "function") { - if (!isSpecNotificationMethod(method)) throw new TypeError(`'${method}' is not a spec notification method; pass schemas as the second argument to setNotificationHandler().`); - this._notificationHandlers.set(method, (notification, codec) => { - const outcome = codec.validateNotification(method, notification); - if (!outcome.ok) { - if (outcome.reason === "not-in-era") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `No wire schema for ${method} in the resolved era`); - throw new Error(outcome.message); - } - return Promise.resolve(schemasOrHandler(outcome.value)); - }); - return; - } - if (!maybeHandler) throw new TypeError("setNotificationHandler: handler is required"); - this._notificationHandlers.set(method, async (notification) => { - const parsed = await validateStandardSchema(schemasOrHandler.params, { ...notification.params }); - if (!parsed.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid params for notification ${method}: ${parsed.error}`); - await maybeHandler(parsed.data, notification); - }); - } - /** - * Removes the notification handler for the given method. - */ - removeNotificationHandler(method) { - this._notificationHandlers.delete(method); - } -}; -function isPlainObject$1(value) { - return value !== null && typeof value === "object" && !Array.isArray(value); -} -function mergeCapabilities(base, additional) { - const result = { ...base }; - for (const key in additional) { - const k = key; - const addValue = additional[k]; - if (addValue === void 0) continue; - const baseValue = result[k]; - result[k] = isPlainObject$1(baseValue) && isPlainObject$1(addValue) ? { - ...baseValue, - ...addValue - } : addValue; - } - return result; -} - -//#endregion -//#region ../core-internal/src/shared/inputRequiredEngine.ts -function src_CX2iR2pK_isPlainObject(value) { - return typeof value === "object" && value !== null && !Array.isArray(value); -} -/** -* Splits a retried request's `inputResponses` map into the BARE response -* entries the spec defines and everything else. The spec's embedded responses -* are the bare result objects (an `ElicitResult`, `CreateMessageResult`, or -* `ListRootsResult`); a wrapped `{method, result}` envelope (a shape some -* peers emit) is never accepted as a response — its key is recorded so the -* handler can re-issue the corresponding input request. -*/ -function partitionInputResponses(inputResponses) { - const accepted = {}; - const droppedKeys = []; - if (!src_CX2iR2pK_isPlainObject(inputResponses)) return { - accepted, - droppedKeys - }; - for (const [key, entry] of Object.entries(inputResponses)) { - if (!src_CX2iR2pK_isPlainObject(entry) || "method" in entry || "result" in entry) { - droppedKeys.push(key); - continue; - } - accepted[key] = entry; - } - return { - accepted, - droppedKeys - }; -} -/** -* Builds the manual-mode {@linkcode InputRequiredResult} value from the -* codec's decoded payload — what an `allowInputRequired: true` caller -* receives instead of the auto-fulfilled complete result. -*/ -function manualInputRequiredValue(decoded) { - return { - resultType: "input_required", - inputRequests: decoded.inputRequests, - ...decoded.requestState !== void 0 && { requestState: decoded.requestState } - }; -} - -//#endregion -//#region ../../node_modules/.pnpm/content-type@1.0.5/node_modules/content-type/index.js -/*! -* content-type -* Copyright(c) 2015 Douglas Christopher Wilson -* MIT Licensed -*/ -var require_content_type = /* @__PURE__ */ __commonJSMin(((exports) => { - /** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ - var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g; - /** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ - var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g; - /** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ - var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/; - exports.parse = parse; - /** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - function parse(string) { - if (!string) throw new TypeError("argument string is required"); - var header = typeof string === "object" ? getcontenttype(string) : string; - if (typeof header !== "string") throw new TypeError("argument string is required to be a string"); - var index = header.indexOf(";"); - var type = index !== -1 ? header.slice(0, index).trim() : header.trim(); - if (!TYPE_REGEXP.test(type)) throw new TypeError("invalid media type"); - var obj = new ContentType(type.toLowerCase()); - if (index !== -1) { - var key; - var match; - var value; - PARAM_REGEXP.lastIndex = index; - while (match = PARAM_REGEXP.exec(header)) { - if (match.index !== index) throw new TypeError("invalid parameter format"); - index += match[0].length; - key = match[1].toLowerCase(); - value = match[2]; - if (value.charCodeAt(0) === 34) { - value = value.slice(1, -1); - if (value.indexOf("\\") !== -1) value = value.replace(QESC_REGEXP, "$1"); - } - obj.parameters[key] = value; - } - if (index !== header.length) throw new TypeError("invalid parameter format"); - } - return obj; - } - /** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - function getcontenttype(obj) { - var header; - if (typeof obj.getHeader === "function") header = obj.getHeader("content-type"); - else if (typeof obj.headers === "object") header = obj.headers && obj.headers["content-type"]; - if (typeof header !== "string") throw new TypeError("content-type header is missing from object"); - return header; - } - /** - * Class to represent a content type. - * @private - */ - function ContentType(type) { - this.parameters = Object.create(null); - this.type = type; - } -})); - -//#endregion -//#region ../core-internal/src/shared/mediaType.ts -var import_content_type = /* @__PURE__ */ __toESM(require_content_type(), 1); -/** -* Extracts the media type (the lowercased `type/subtype` pair, without -* parameters) from a raw `Content-Type` header value, or `undefined` when the -* header is missing or empty. -* -* Content-Type comparisons must use the parsed media type, never a substring -* search of the raw header: a value like `text/plain; a=application/json` -* contains the substring `application/json` but its media type is -* `text/plain`, and case variants or parameters make naive string comparison -* wrong in both directions. -* -* "Essence" is the WHATWG MIME Sniffing standard's term for the bare -* `type/subtype` pair (https://mimesniff.spec.whatwg.org/#mime-type-essence); -* the Fetch standard's request classification is defined against it -* (https://fetch.spec.whatwg.org/#cors-safelisted-request-header). -* -* Parsing is RFC 9110 (`content-type` package) first. When the parameter -* section is malformed (`application/json;`, `application/json; charset=`), -* browsers and most HTTP stacks still derive the media type from the segment -* before the first `;` — the fallback matches that widely-implemented -* behavior, so a header whose media type is unambiguous is not rejected for -* a sloppy parameter section. -*/ -function src_CX2iR2pK_mediaTypeEssence(header) { - if (!header) return; - try { - return import_content_type.parse(header).type; - } catch { - const essence = (header.split(";", 1)[0] ?? "").trim().toLowerCase(); - if (essence === "" || header.slice(essence.length).includes(",")) return; - return essence; - } -} -/** -* Whether a raw `Content-Type` header value denotes `application/json`. -* Parameters (for example `charset=utf-8`) are allowed and ignored; malformed -* parameter sections do not reject a header whose media type is unambiguously -* `application/json` (see `mediaTypeEssence` for the exact grammar). -*/ -function src_CX2iR2pK_isJsonContentType(header) { - if (header === "application/json") return true; - return src_CX2iR2pK_mediaTypeEssence(header) === "application/json"; -} - -//#endregion -//#region ../core-internal/src/shared/metadataUtils.ts -/** -* Utilities for working with {@linkcode BaseMetadata} objects. -*/ -/** -* Gets the display name for an object with {@linkcode BaseMetadata}. -* For tools, the precedence is: `title` → {@linkcode index.ToolAnnotations | annotations}.`title` → `name` -* For other objects: `title` → `name` -* This implements the spec requirement: "if no title is provided, name should be used for display purposes" -*/ -function getDisplayName(metadata) { - if (metadata.title !== void 0 && metadata.title !== "") return metadata.title; - if ("annotations" in metadata && metadata.annotations?.title) return metadata.annotations.title; - return metadata.name; -} - -//#endregion -//#region ../core-internal/src/shared/stdio.ts -const STDIO_DEFAULT_MAX_BUFFER_SIZE = 10 * 1024 * 1024; -/** -* Buffers a continuous stdio stream into discrete JSON-RPC messages. -*/ -var ReadBuffer = class { - _buffer; - _maxBufferSize; - constructor(options) { - this._maxBufferSize = options?.maxBufferSize ?? STDIO_DEFAULT_MAX_BUFFER_SIZE; - } - append(chunk) { - if ((this._buffer?.length ?? 0) + chunk.length > this._maxBufferSize) { - this.clear(); - throw new Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`); - } - this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk; - } - readMessage() { - while (this._buffer) { - const index = this._buffer.indexOf("\n"); - if (index === -1) return null; - const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, ""); - this._buffer = this._buffer.subarray(index + 1); - try { - return deserializeMessage(line); - } catch (error) { - if (error instanceof SyntaxError) continue; - throw error; - } - } - return null; - } - clear() { - this._buffer = void 0; - } -}; -function deserializeMessage(line) { - return auth_CUe6YdwF_JSONRPCMessageSchema.parse(JSON.parse(line)); -} -function serializeMessage(message) { - return JSON.stringify(message) + "\n"; -} - -//#endregion -//#region ../core-internal/src/shared/toolNameValidation.ts -/** -* Tool name validation utilities according to SEP: Specify Format for Tool Names -* -* Tool names SHOULD be between 1 and 128 characters in length (inclusive). -* Tool names are case-sensitive. -* Allowed characters: uppercase and lowercase ASCII letters (`A-Z`, `a-z`), digits -* (`0-9`), underscore (`_`), dash (`-`), and dot (`.`). -* Tool names SHOULD NOT contain spaces, commas, or other special characters. -* -* @see {@link https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986 | SEP-986: Specify Format for Tool Names} -*/ -/** -* Regular expression for valid tool names according to SEP-986 specification -*/ -const TOOL_NAME_REGEX = /^[A-Za-z0-9._-]{1,128}$/; -/** -* Validates a tool name according to the SEP specification -* @param name - The tool name to validate -* @returns An object containing validation result and any warnings -*/ -function validateToolName(name) { - const warnings = []; - if (name.length === 0) return { - isValid: false, - warnings: ["Tool name cannot be empty"] - }; - if (name.length > 128) return { - isValid: false, - warnings: [`Tool name exceeds maximum length of 128 characters (current: ${name.length})`] - }; - if (name.includes(" ")) warnings.push("Tool name contains spaces, which may cause parsing issues"); - if (name.includes(",")) warnings.push("Tool name contains commas, which may cause parsing issues"); - if (name.startsWith("-") || name.endsWith("-")) warnings.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"); - if (name.startsWith(".") || name.endsWith(".")) warnings.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"); - if (!TOOL_NAME_REGEX.test(name)) { - const invalidChars = [...name].filter((char) => !/[A-Za-z0-9._-]/.test(char)).filter((char, index, arr) => arr.indexOf(char) === index); - warnings.push(`Tool name contains invalid characters: ${invalidChars.map((c) => `"${c}"`).join(", ")}`, "Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"); - return { - isValid: false, - warnings - }; - } - return { - isValid: true, - warnings - }; -} -/** -* Issues warnings for non-conforming tool names -* @param name - The tool name that triggered the warnings -* @param warnings - Array of warning messages -*/ -function issueToolNameWarning(name, warnings) { - if (warnings.length > 0) { - console.warn(`Tool name validation warning for "${name}":`); - for (const warning of warnings) console.warn(` - ${warning}`); - console.warn("Tool registration will proceed, but this may cause compatibility issues."); - console.warn("Consider updating the tool name to conform to the MCP tool naming standard."); - console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details."); - } -} -/** -* Validates a tool name and issues warnings for non-conforming names -* @param name - The tool name to validate -* @returns `true` if the name is valid, `false` otherwise -*/ -function validateAndWarnToolName(name) { - const result = validateToolName(name); - issueToolNameWarning(name, result.warnings); - return result.isValid; -} - -//#endregion -//#region ../core-internal/src/shared/transport.ts -/** -* Normalizes `HeadersInit` to a plain `Record` for manipulation. -* Handles `Headers` objects, arrays of tuples, and plain objects. -*/ -function normalizeHeaders(headers) { - if (!headers) return {}; - if (headers instanceof Headers) return Object.fromEntries(headers.entries()); - if (Array.isArray(headers)) return Object.fromEntries(headers); - return { ...headers }; -} -/** -* Creates a fetch function that includes base `RequestInit` options. -* This ensures requests inherit settings like credentials, mode, headers, etc. from the base init. -* -* @param baseFetch - The base fetch function to wrap (defaults to global `fetch`) -* @param baseInit - The base `RequestInit` to merge with each request -* @returns A wrapped fetch function that merges base options with call-specific options -*/ -function createFetchWithInit(baseFetch = fetch, baseInit) { - if (!baseInit) return baseFetch; - return async (url, init) => { - return baseFetch(url, { - ...baseInit, - ...init, - headers: init?.headers ? { - ...normalizeHeaders(baseInit.headers), - ...normalizeHeaders(init.headers) - } : baseInit.headers - }); - }; -} - -//#endregion -//#region ../core-internal/src/shared/uriTemplate.ts -const MAX_TEMPLATE_LENGTH = 1e6; -const MAX_VARIABLE_LENGTH = 1e6; -const MAX_TEMPLATE_EXPRESSIONS = 1e4; -const MAX_REGEX_LENGTH = 1e6; -var src_CX2iR2pK_UriTemplate = class UriTemplate { - /** - * Returns true if the given string contains any URI template expressions. - * A template expression is a sequence of characters enclosed in curly braces, - * like `{foo}` or `{?bar}`. - */ - static isTemplate(str) { - return /\{[^}\s]+\}/.test(str); - } - static validateLength(str, max, context) { - if (str.length > max) throw new Error(`${context} exceeds maximum length of ${max} characters (got ${str.length})`); - } - template; - parts; - get variableNames() { - return this.parts.flatMap((part) => typeof part === "string" ? [] : part.names); - } - constructor(template) { - UriTemplate.validateLength(template, MAX_TEMPLATE_LENGTH, "Template"); - this.template = template; - this.parts = this.parse(template); - } - toString() { - return this.template; - } - parse(template) { - const parts = []; - let currentText = ""; - let i = 0; - let expressionCount = 0; - while (i < template.length) if (template[i] === "{") { - if (currentText) { - parts.push(currentText); - currentText = ""; - } - const end = template.indexOf("}", i); - if (end === -1) throw new Error("Unclosed template expression"); - expressionCount++; - if (expressionCount > MAX_TEMPLATE_EXPRESSIONS) throw new Error(`Template contains too many expressions (max ${MAX_TEMPLATE_EXPRESSIONS})`); - const expr = template.slice(i + 1, end); - const operator = this.getOperator(expr); - const exploded = expr.includes("*"); - const names = this.getNames(expr); - const name = names[0]; - for (const name$1 of names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - parts.push({ - name, - operator, - names, - exploded - }); - i = end + 1; - } else { - currentText += template[i]; - i++; - } - if (currentText) parts.push(currentText); - return parts; - } - getOperator(expr) { - return [ - "+", - "#", - ".", - "/", - "?", - "&" - ].find((op) => expr.startsWith(op)) || ""; - } - getNames(expr) { - const operator = this.getOperator(expr); - return expr.slice(operator.length).split(",").map((name) => name.replace("*", "").trim()).filter((name) => name.length > 0); - } - encodeValue(value, operator) { - UriTemplate.validateLength(value, MAX_VARIABLE_LENGTH, "Variable value"); - if (operator === "+" || operator === "#") return encodeURI(value); - return encodeURIComponent(value); - } - expandPart(part, variables) { - if (part.operator === "?" || part.operator === "&") { - const pairs = part.names.map((name) => { - const value$1 = variables[name]; - if (value$1 === void 0) return ""; - return `${name}=${Array.isArray(value$1) ? value$1.map((v) => this.encodeValue(v, part.operator)).join(",") : this.encodeValue(value$1.toString(), part.operator)}`; - }).filter((pair) => pair.length > 0); - if (pairs.length === 0) return ""; - return (part.operator === "?" ? "?" : "&") + pairs.join("&"); - } - if (part.names.length > 1) { - const values = part.names.map((name) => variables[name]).filter((v) => v !== void 0); - if (values.length === 0) return ""; - return values.map((v) => Array.isArray(v) ? v[0] : v).join(","); - } - const value = variables[part.name]; - if (value === void 0) return ""; - const encoded = (Array.isArray(value) ? value : [value]).map((v) => this.encodeValue(v, part.operator)); - switch (part.operator) { - case "": return encoded.join(","); - case "+": return encoded.join(","); - case "#": return "#" + encoded.join(","); - case ".": return "." + encoded.join("."); - case "/": return "/" + encoded.join("/"); - default: return encoded.join(","); - } - } - expand(variables) { - let result = ""; - let hasQueryParam = false; - for (const part of this.parts) { - if (typeof part === "string") { - result += part; - continue; - } - const expanded = this.expandPart(part, variables); - if (!expanded) continue; - result += (part.operator === "?" || part.operator === "&") && hasQueryParam ? expanded.replace("?", "&") : expanded; - if (part.operator === "?" || part.operator === "&") hasQueryParam = true; - } - return result; - } - escapeRegExp(str) { - return str.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); - } - partToRegExp(part) { - const patterns = []; - for (const name$1 of part.names) UriTemplate.validateLength(name$1, MAX_VARIABLE_LENGTH, "Variable name"); - if (part.operator === "?" || part.operator === "&") { - for (let i = 0; i < part.names.length; i++) { - const name$1 = part.names[i]; - const prefix = i === 0 ? "\\" + part.operator : "&"; - patterns.push({ - pattern: prefix + this.escapeRegExp(name$1) + "=([^&]+)", - name: name$1 - }); - } - return patterns; - } - let pattern; - const name = part.name; - switch (part.operator) { - case "": - pattern = part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"; - break; - case "+": - case "#": - pattern = "(.+)"; - break; - case ".": - pattern = String.raw`\.([^/,]+)`; - break; - case "/": - pattern = "/" + (part.exploded ? "([^/,]+(?:,[^/,]+)*)" : "([^/,]+)"); - break; - default: pattern = "([^/]+)"; - } - patterns.push({ - pattern, - name - }); - return patterns; - } - match(uri) { - UriTemplate.validateLength(uri, MAX_TEMPLATE_LENGTH, "URI"); - let pattern = "^"; - const names = []; - for (const part of this.parts) if (typeof part === "string") pattern += this.escapeRegExp(part); - else { - const patterns = this.partToRegExp(part); - for (const { pattern: partPattern, name } of patterns) { - pattern += partPattern; - names.push({ - name, - exploded: part.exploded - }); - } - } - pattern += "$"; - UriTemplate.validateLength(pattern, MAX_REGEX_LENGTH, "Generated regex pattern"); - const regex = new RegExp(pattern); - const match = uri.match(regex); - if (!match) return null; - const result = {}; - for (const [i, name_] of names.entries()) { - const { name, exploded } = name_; - const value = match[i + 1]; - const cleanName = name.replace("*", ""); - result[cleanName] = exploded && value.includes(",") ? value.split(",") : value; - } - return result; - } -}; - -//#endregion -//#region ../core-internal/src/util/inMemory.ts -/** -* In-memory transport for creating clients and servers that talk to each other within the same process. -* -* Intended for testing and development. For production in-process connections, use -* `StreamableHTTPClientTransport` against a local server URL. -*/ -var src_CX2iR2pK_InMemoryTransport = class InMemoryTransport { - _otherTransport; - _messageQueue = []; - _closed = false; - onclose; - onerror; - onmessage; - sessionId; - /** - * Creates a pair of linked in-memory transports that can communicate with each other. One should be passed to a {@linkcode @modelcontextprotocol/client!client/client.Client | Client} and one to a {@linkcode @modelcontextprotocol/server!server/server.Server | Server}. - */ - static createLinkedPair() { - const clientTransport = new InMemoryTransport(); - const serverTransport = new InMemoryTransport(); - clientTransport._otherTransport = serverTransport; - serverTransport._otherTransport = clientTransport; - return [clientTransport, serverTransport]; - } - async start() { - while (this._messageQueue.length > 0) { - const queuedMessage = this._messageQueue.shift(); - this.onmessage?.(queuedMessage.message, queuedMessage.extra); - } - } - async close() { - if (this._closed) return; - this._closed = true; - const other = this._otherTransport; - this._otherTransport = void 0; - try { - await other?.close(); - } finally { - this.onclose?.(); - } - } - /** - * Sends a message with optional auth info. - * This is useful for testing authentication scenarios. - */ - async send(message, options) { - if (!this._otherTransport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.NotConnected, "Not connected"); - if (this._otherTransport.onmessage) this._otherTransport.onmessage(message, { authInfo: options?.authInfo }); - else this._otherTransport._messageQueue.push({ - message, - extra: { authInfo: options?.authInfo } - }); - } -}; - -//#endregion -//#region ../core-internal/src/util/zodCompat.ts -/** -* Zod-specific helpers for the v1-compat raw-shape shorthand on -* `registerTool`/`registerPrompt`. Kept separate from `standardSchema.ts` so -* that file stays library-agnostic per the Standard Schema spec. -*/ -function isZodV4Schema(v) { - return typeof v === "object" && v !== null && "_zod" in v; -} -function looksLikeZodV3(v) { - return typeof v === "object" && v !== null && !("_zod" in v) && "_def" in v && typeof v._def?.typeName === "string"; -} -/** -* Detects a "raw shape" — a plain object whose values are Zod field schemas, -* e.g. `{ name: z.string() }`. Powers the auto-wrap in -* {@linkcode normalizeRawShapeSchema}, which wraps with `z.object()`, so only -* Zod values are supported. -* -* @internal -*/ -function isZodRawShape(obj) { - if (typeof obj !== "object" || obj === null) return false; - if (isStandardSchema(obj)) return false; - const proto = Object.getPrototypeOf(obj); - if (proto !== Object.prototype && proto !== null) return false; - return Object.values(obj).every((v) => isZodV4Schema(v)); -} -/** -* Accepts either a {@linkcode StandardSchemaWithJSON} or a raw Zod shape -* `{ field: z.string() }` and returns a {@linkcode StandardSchemaWithJSON}. -* Raw shapes are wrapped with `z.object()` so the rest of the pipeline sees a -* uniform schema type; already-wrapped schemas pass through unchanged. -* -* @internal -*/ -function normalizeRawShapeSchema(schema) { - if (schema === void 0) return void 0; - if (isZodRawShape(schema)) return schemas_object(schema); - if (typeof schema === "object" && schema !== null && !isStandardSchema(schema) && Object.values(schema).some((v) => looksLikeZodV3(v))) throw new TypeError("Raw-shape inputSchema/outputSchema/argsSchema fields must be Zod v4 schemas. Got a Zod v3 field schema. Import from `zod/v4` (or upgrade your zod import), or wrap with `z.object({...})` yourself."); - if (!isStandardSchema(schema)) throw new TypeError("inputSchema/outputSchema/argsSchema must be a Standard Schema (e.g. z.object({...})) or a raw Zod shape ({ field: z.string() })."); - return schema; -} - -//#endregion -//#region ../core-internal/src/wire/preload.ts -/** -* Explicit warm-up entry for the lazy wire-schema layers. -* -* The per-revision wire schemas are built lazily: each era's schema set sits -* behind a memoized factory (`buildSchemas2025`/`buildSchemas2026`), and the -* registry/codec lookup maps above those factories are memoized the same way. -* That laziness is the right default on process-per-invocation runtimes (CLI -* tools, dev servers), where module evaluation IS startup latency and most -* short-lived processes never validate a message on both eras. -* -* On platforms that bill request CPU but not module evaluation — isolate-based -* edge/serverless runtimes such as Cloudflare Workers — the trade inverts: -* module-scope work runs during isolate warm-up outside any request, while -* lazy construction lands inside the first request's billed (and latency -* budgeted) CPU. `preloadSchemas()` lets deployments on such platforms move -* the one-time construction cost back to module scope by calling it at module -* scope themselves. The packages' own workerd shims already do this, so -* Workers deployments get eager construction automatically. -*/ -/** -* Eagerly builds every lazily-constructed wire-schema layer, so that no later -* validation pays schema-construction cost. -* -* Synchronous and idempotent: every layer is a memo, so the first call does -* all the work and subsequent calls return immediately. Reference identity is -* unaffected — this forces the same memos every lazy consumer pulls through. -* -* Call it at module scope on platforms that bill per-request CPU but not -* module evaluation (isolate-based edge/serverless runtimes), where deferring -* construction would move it into the first request of every fresh isolate: -* -* ```ts -* // from '@modelcontextprotocol/server' or '@modelcontextprotocol/client' — -* // each package bundles its own schema copy, so warm the one(s) you import. -* preloadSchemas(); // module scope — runs during isolate warm-up -* ``` -* -* On Node CLIs and other process-per-invocation runtimes, prefer the lazy -* default — there, module-scope construction is pure added boot latency. -*/ -function preloadSchemas() { - buildSchemas2025(); - buildSchemas2026(); - warmRegistryMaps2025(); - warmInputSchemaMaps2026(); - warmWireResultSchemas2026(); -} - -//#endregion -//#region ../core-internal/src/validators/fromJsonSchema.ts -/** -* Wrap a raw JSON Schema object as a {@linkcode StandardSchemaWithJSON} so it can be -* passed to `registerTool` / `registerPrompt`. Use this when you already have JSON -* Schema (e.g. from TypeBox, or hand-written) and want to register it without going -* through a Standard Schema library. -* -* The callback arguments will be typed `unknown` (raw JSON Schema has no TypeScript -* types attached). Cast at the call site, or use the generic `fromJsonSchema(...)`. -* -* @param schema - A JSON Schema object describing the expected shape -* @param validator - A validator provider. When importing `fromJsonSchema` from -* `@modelcontextprotocol/server` or `@modelcontextprotocol/client`, a runtime-appropriate -* default is provided automatically (AJV on Node.js, CfWorker on edge runtimes). -* -* @example -* ```ts source="./fromJsonSchema.examples.ts#fromJsonSchema_basicUsage" -* const inputSchema = fromJsonSchema<{ name: string }>( -* { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] }, -* validator -* ); -* // Use with server.registerTool('greet', { inputSchema }, handler) -* ``` -*/ -function fromJsonSchema(schema, validator) { - const check = validator.getValidator(schema); - return { "~standard": { - version: 1, - vendor: "mcp", - jsonSchema: { - input: () => schema, - output: () => schema - }, - validate: (data) => { - const result = check(data); - return result.valid ? { value: result.data } : { issues: [{ message: result.errorMessage }] }; - } - } }; -} - -//#endregion - -//# sourceMappingURL=src-CX2iR2pK.mjs.map - - - -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/code.js -var require_code$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0; - var _CodeOrName = class {}; - exports._CodeOrName = _CodeOrName; - exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i; - var Name = class extends _CodeOrName { - constructor(s) { - super(); - if (!exports.IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier"); - this.str = s; - } - toString() { - return this.str; - } - emptyStr() { - return false; - } - get names() { - return { [this.str]: 1 }; - } - }; - exports.Name = Name; - var _Code = class extends _CodeOrName { - constructor(code) { - super(); - this._items = typeof code === "string" ? [code] : code; - } - toString() { - return this.str; - } - emptyStr() { - if (this._items.length > 1) return false; - const item = this._items[0]; - return item === "" || item === "\"\""; - } - get str() { - var _a; - return (_a = this._str) !== null && _a !== void 0 ? _a : this._str = this._items.reduce((s, c) => `${s}${c}`, ""); - } - get names() { - var _a; - return (_a = this._names) !== null && _a !== void 0 ? _a : this._names = this._items.reduce((names, c) => { - if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1; - return names; - }, {}); - } - }; - exports._Code = _Code; - exports.nil = new _Code(""); - function _(strs, ...args) { - const code = [strs[0]]; - let i = 0; - while (i < args.length) { - addCodeArg(code, args[i]); - code.push(strs[++i]); - } - return new _Code(code); - } - exports._ = _; - const plus = new _Code("+"); - function str(strs, ...args) { - const expr = [safeStringify(strs[0])]; - let i = 0; - while (i < args.length) { - expr.push(plus); - addCodeArg(expr, args[i]); - expr.push(plus, safeStringify(strs[++i])); - } - optimize(expr); - return new _Code(expr); - } - exports.str = str; - function addCodeArg(code, arg) { - if (arg instanceof _Code) code.push(...arg._items); - else if (arg instanceof Name) code.push(arg); - else code.push(interpolate(arg)); - } - exports.addCodeArg = addCodeArg; - function optimize(expr) { - let i = 1; - while (i < expr.length - 1) { - if (expr[i] === plus) { - const res = mergeExprItems(expr[i - 1], expr[i + 1]); - if (res !== void 0) { - expr.splice(i - 1, 3, res); - continue; - } - expr[i++] = "+"; - } - i++; - } - } - function mergeExprItems(a, b) { - if (b === "\"\"") return a; - if (a === "\"\"") return b; - if (typeof a == "string") { - if (b instanceof Name || a[a.length - 1] !== "\"") return; - if (typeof b != "string") return `${a.slice(0, -1)}${b}"`; - if (b[0] === "\"") return a.slice(0, -1) + b.slice(1); - return; - } - if (typeof b == "string" && b[0] === "\"" && !(a instanceof Name)) return `"${a}${b.slice(1)}`; - } - function strConcat(c1, c2) { - return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`; - } - exports.strConcat = strConcat; - function interpolate(x) { - return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x); - } - function stringify(x) { - return new _Code(safeStringify(x)); - } - exports.stringify = stringify; - function safeStringify(x) { - return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029"); - } - exports.safeStringify = safeStringify; - function getProperty(key) { - return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _`[${key}]`; - } - exports.getProperty = getProperty; - function getEsmExportName(key) { - if (typeof key == "string" && exports.IDENTIFIER.test(key)) return new _Code(`${key}`); - throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`); - } - exports.getEsmExportName = getEsmExportName; - function regexpCode(rx) { - return new _Code(rx.toString()); - } - exports.regexpCode = regexpCode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/scope.js -var require_scope = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0; - const code_1 = require_code$1(); - var ValueError = class extends Error { - constructor(name) { - super(`CodeGen: "code" for ${name} not defined`); - this.value = name.value; - } - }; - var UsedValueState; - (function(UsedValueState) { - UsedValueState[UsedValueState["Started"] = 0] = "Started"; - UsedValueState[UsedValueState["Completed"] = 1] = "Completed"; - })(UsedValueState || (exports.UsedValueState = UsedValueState = {})); - exports.varKinds = { - const: new code_1.Name("const"), - let: new code_1.Name("let"), - var: new code_1.Name("var") - }; - var Scope = class { - constructor({ prefixes, parent } = {}) { - this._names = {}; - this._prefixes = prefixes; - this._parent = parent; - } - toName(nameOrPrefix) { - return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix); - } - name(prefix) { - return new code_1.Name(this._newName(prefix)); - } - _newName(prefix) { - const ng = this._names[prefix] || this._nameGroup(prefix); - return `${prefix}${ng.index++}`; - } - _nameGroup(prefix) { - var _a, _b; - if (((_b = (_a = this._parent) === null || _a === void 0 ? void 0 : _a._prefixes) === null || _b === void 0 ? void 0 : _b.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`); - return this._names[prefix] = { - prefix, - index: 0 - }; - } - }; - exports.Scope = Scope; - var ValueScopeName = class extends code_1.Name { - constructor(prefix, nameStr) { - super(nameStr); - this.prefix = prefix; - } - setValue(value, { property, itemIndex }) { - this.value = value; - this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`; - } - }; - exports.ValueScopeName = ValueScopeName; - const line = (0, code_1._)`\n`; - var ValueScope = class extends Scope { - constructor(opts) { - super(opts); - this._values = {}; - this._scope = opts.scope; - this.opts = { - ...opts, - _n: opts.lines ? line : code_1.nil - }; - } - get() { - return this._scope; - } - name(prefix) { - return new ValueScopeName(prefix, this._newName(prefix)); - } - value(nameOrPrefix, value) { - var _a; - if (value.ref === void 0) throw new Error("CodeGen: ref must be passed in value"); - const name = this.toName(nameOrPrefix); - const { prefix } = name; - const valueKey = (_a = value.key) !== null && _a !== void 0 ? _a : value.ref; - let vs = this._values[prefix]; - if (vs) { - const _name = vs.get(valueKey); - if (_name) return _name; - } else vs = this._values[prefix] = /* @__PURE__ */ new Map(); - vs.set(valueKey, name); - const s = this._scope[prefix] || (this._scope[prefix] = []); - const itemIndex = s.length; - s[itemIndex] = value.ref; - name.setValue(value, { - property: prefix, - itemIndex - }); - return name; - } - getValue(prefix, keyOrRef) { - const vs = this._values[prefix]; - if (!vs) return; - return vs.get(keyOrRef); - } - scopeRefs(scopeName, values = this._values) { - return this._reduceValues(values, (name) => { - if (name.scopePath === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return (0, code_1._)`${scopeName}${name.scopePath}`; - }); - } - scopeCode(values = this._values, usedValues, getCode) { - return this._reduceValues(values, (name) => { - if (name.value === void 0) throw new Error(`CodeGen: name "${name}" has no value`); - return name.value.code; - }, usedValues, getCode); - } - _reduceValues(values, valueCode, usedValues = {}, getCode) { - let code = code_1.nil; - for (const prefix in values) { - const vs = values[prefix]; - if (!vs) continue; - const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map(); - vs.forEach((name) => { - if (nameSet.has(name)) return; - nameSet.set(name, UsedValueState.Started); - let c = valueCode(name); - if (c) { - const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const; - code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`; - } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) code = (0, code_1._)`${code}${c}${this.opts._n}`; - else throw new ValueError(name); - nameSet.set(name, UsedValueState.Completed); - }); - } - return code; - } - }; - exports.ValueScope = ValueScope; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/codegen/index.js -var require_codegen = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0; - const code_1 = require_code$1(); - const scope_1 = require_scope(); - var code_2 = require_code$1(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return code_2._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return code_2.str; - } - }); - Object.defineProperty(exports, "strConcat", { - enumerable: true, - get: function() { - return code_2.strConcat; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return code_2.nil; - } - }); - Object.defineProperty(exports, "getProperty", { - enumerable: true, - get: function() { - return code_2.getProperty; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return code_2.stringify; - } - }); - Object.defineProperty(exports, "regexpCode", { - enumerable: true, - get: function() { - return code_2.regexpCode; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return code_2.Name; - } - }); - var scope_2 = require_scope(); - Object.defineProperty(exports, "Scope", { - enumerable: true, - get: function() { - return scope_2.Scope; - } - }); - Object.defineProperty(exports, "ValueScope", { - enumerable: true, - get: function() { - return scope_2.ValueScope; - } - }); - Object.defineProperty(exports, "ValueScopeName", { - enumerable: true, - get: function() { - return scope_2.ValueScopeName; - } - }); - Object.defineProperty(exports, "varKinds", { - enumerable: true, - get: function() { - return scope_2.varKinds; - } - }); - exports.operators = { - GT: new code_1._Code(">"), - GTE: new code_1._Code(">="), - LT: new code_1._Code("<"), - LTE: new code_1._Code("<="), - EQ: new code_1._Code("==="), - NEQ: new code_1._Code("!=="), - NOT: new code_1._Code("!"), - OR: new code_1._Code("||"), - AND: new code_1._Code("&&"), - ADD: new code_1._Code("+") - }; - var Node = class { - optimizeNodes() { - return this; - } - optimizeNames(_names, _constants) { - return this; - } - }; - var Def = class extends Node { - constructor(varKind, name, rhs) { - super(); - this.varKind = varKind; - this.name = name; - this.rhs = rhs; - } - render({ es5, _n }) { - const varKind = es5 ? scope_1.varKinds.var : this.varKind; - const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`; - return `${varKind} ${this.name}${rhs};` + _n; - } - optimizeNames(names, constants) { - if (!names[this.name.str]) return; - if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {}; - } - }; - var Assign = class extends Node { - constructor(lhs, rhs, sideEffects) { - super(); - this.lhs = lhs; - this.rhs = rhs; - this.sideEffects = sideEffects; - } - render({ _n }) { - return `${this.lhs} = ${this.rhs};` + _n; - } - optimizeNames(names, constants) { - if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects) return; - this.rhs = optimizeExpr(this.rhs, names, constants); - return this; - } - get names() { - return addExprNames(this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names }, this.rhs); - } - }; - var AssignOp = class extends Assign { - constructor(lhs, op, rhs, sideEffects) { - super(lhs, rhs, sideEffects); - this.op = op; - } - render({ _n }) { - return `${this.lhs} ${this.op}= ${this.rhs};` + _n; - } - }; - var Label = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `${this.label}:` + _n; - } - }; - var Break = class extends Node { - constructor(label) { - super(); - this.label = label; - this.names = {}; - } - render({ _n }) { - return `break${this.label ? ` ${this.label}` : ""};` + _n; - } - }; - var Throw = class extends Node { - constructor(error) { - super(); - this.error = error; - } - render({ _n }) { - return `throw ${this.error};` + _n; - } - get names() { - return this.error.names; - } - }; - var AnyCode = class extends Node { - constructor(code) { - super(); - this.code = code; - } - render({ _n }) { - return `${this.code};` + _n; - } - optimizeNodes() { - return `${this.code}` ? this : void 0; - } - optimizeNames(names, constants) { - this.code = optimizeExpr(this.code, names, constants); - return this; - } - get names() { - return this.code instanceof code_1._CodeOrName ? this.code.names : {}; - } - }; - var ParentNode = class extends Node { - constructor(nodes = []) { - super(); - this.nodes = nodes; - } - render(opts) { - return this.nodes.reduce((code, n) => code + n.render(opts), ""); - } - optimizeNodes() { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i].optimizeNodes(); - if (Array.isArray(n)) nodes.splice(i, 1, ...n); - else if (n) nodes[i] = n; - else nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - optimizeNames(names, constants) { - const { nodes } = this; - let i = nodes.length; - while (i--) { - const n = nodes[i]; - if (n.optimizeNames(names, constants)) continue; - subtractNames(names, n.names); - nodes.splice(i, 1); - } - return nodes.length > 0 ? this : void 0; - } - get names() { - return this.nodes.reduce((names, n) => addNames(names, n.names), {}); - } - }; - var BlockNode = class extends ParentNode { - render(opts) { - return "{" + opts._n + super.render(opts) + "}" + opts._n; - } - }; - var Root = class extends ParentNode {}; - var Else = class extends BlockNode {}; - Else.kind = "else"; - var If = class If extends BlockNode { - constructor(condition, nodes) { - super(nodes); - this.condition = condition; - } - render(opts) { - let code = `if(${this.condition})` + super.render(opts); - if (this.else) code += "else " + this.else.render(opts); - return code; - } - optimizeNodes() { - super.optimizeNodes(); - const cond = this.condition; - if (cond === true) return this.nodes; - let e = this.else; - if (e) { - const ns = e.optimizeNodes(); - e = this.else = Array.isArray(ns) ? new Else(ns) : ns; - } - if (e) { - if (cond === false) return e instanceof If ? e : e.nodes; - if (this.nodes.length) return this; - return new If(not(cond), e instanceof If ? [e] : e.nodes); - } - if (cond === false || !this.nodes.length) return void 0; - return this; - } - optimizeNames(names, constants) { - var _a; - this.else = (_a = this.else) === null || _a === void 0 ? void 0 : _a.optimizeNames(names, constants); - if (!(super.optimizeNames(names, constants) || this.else)) return; - this.condition = optimizeExpr(this.condition, names, constants); - return this; - } - get names() { - const names = super.names; - addExprNames(names, this.condition); - if (this.else) addNames(names, this.else.names); - return names; - } - }; - If.kind = "if"; - var For = class extends BlockNode {}; - For.kind = "for"; - var ForLoop = class extends For { - constructor(iteration) { - super(); - this.iteration = iteration; - } - render(opts) { - return `for(${this.iteration})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iteration = optimizeExpr(this.iteration, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iteration.names); - } - }; - var ForRange = class extends For { - constructor(varKind, name, from, to) { - super(); - this.varKind = varKind; - this.name = name; - this.from = from; - this.to = to; - } - render(opts) { - const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind; - const { name, from, to } = this; - return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts); - } - get names() { - return addExprNames(addExprNames(super.names, this.from), this.to); - } - }; - var ForIter = class extends For { - constructor(loop, varKind, name, iterable) { - super(); - this.loop = loop; - this.varKind = varKind; - this.name = name; - this.iterable = iterable; - } - render(opts) { - return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts); - } - optimizeNames(names, constants) { - if (!super.optimizeNames(names, constants)) return; - this.iterable = optimizeExpr(this.iterable, names, constants); - return this; - } - get names() { - return addNames(super.names, this.iterable.names); - } - }; - var Func = class extends BlockNode { - constructor(name, args, async) { - super(); - this.name = name; - this.args = args; - this.async = async; - } - render(opts) { - return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render(opts); - } - }; - Func.kind = "func"; - var Return = class extends ParentNode { - render(opts) { - return "return " + super.render(opts); - } - }; - Return.kind = "return"; - var Try = class extends BlockNode { - render(opts) { - let code = "try" + super.render(opts); - if (this.catch) code += this.catch.render(opts); - if (this.finally) code += this.finally.render(opts); - return code; - } - optimizeNodes() { - var _a, _b; - super.optimizeNodes(); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNodes(); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNodes(); - return this; - } - optimizeNames(names, constants) { - var _a, _b; - super.optimizeNames(names, constants); - (_a = this.catch) === null || _a === void 0 || _a.optimizeNames(names, constants); - (_b = this.finally) === null || _b === void 0 || _b.optimizeNames(names, constants); - return this; - } - get names() { - const names = super.names; - if (this.catch) addNames(names, this.catch.names); - if (this.finally) addNames(names, this.finally.names); - return names; - } - }; - var Catch = class extends BlockNode { - constructor(error) { - super(); - this.error = error; - } - render(opts) { - return `catch(${this.error})` + super.render(opts); - } - }; - Catch.kind = "catch"; - var Finally = class extends BlockNode { - render(opts) { - return "finally" + super.render(opts); - } - }; - Finally.kind = "finally"; - var CodeGen = class { - constructor(extScope, opts = {}) { - this._values = {}; - this._blockStarts = []; - this._constants = {}; - this.opts = { - ...opts, - _n: opts.lines ? "\n" : "" - }; - this._extScope = extScope; - this._scope = new scope_1.Scope({ parent: extScope }); - this._nodes = [new Root()]; - } - toString() { - return this._root.render(this.opts); - } - name(prefix) { - return this._scope.name(prefix); - } - scopeName(prefix) { - return this._extScope.name(prefix); - } - scopeValue(prefixOrName, value) { - const name = this._extScope.value(prefixOrName, value); - (this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set())).add(name); - return name; - } - getScopeValue(prefix, keyOrRef) { - return this._extScope.getValue(prefix, keyOrRef); - } - scopeRefs(scopeName) { - return this._extScope.scopeRefs(scopeName, this._values); - } - scopeCode() { - return this._extScope.scopeCode(this._values); - } - _def(varKind, nameOrPrefix, rhs, constant) { - const name = this._scope.toName(nameOrPrefix); - if (rhs !== void 0 && constant) this._constants[name.str] = rhs; - this._leafNode(new Def(varKind, name, rhs)); - return name; - } - const(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant); - } - let(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant); - } - var(nameOrPrefix, rhs, _constant) { - return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant); - } - assign(lhs, rhs, sideEffects) { - return this._leafNode(new Assign(lhs, rhs, sideEffects)); - } - add(lhs, rhs) { - return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs)); - } - code(c) { - if (typeof c == "function") c(); - else if (c !== code_1.nil) this._leafNode(new AnyCode(c)); - return this; - } - object(...keyValues) { - const code = ["{"]; - for (const [key, value] of keyValues) { - if (code.length > 1) code.push(","); - code.push(key); - if (key !== value || this.opts.es5) { - code.push(":"); - (0, code_1.addCodeArg)(code, value); - } - } - code.push("}"); - return new code_1._Code(code); - } - if(condition, thenBody, elseBody) { - this._blockNode(new If(condition)); - if (thenBody && elseBody) this.code(thenBody).else().code(elseBody).endIf(); - else if (thenBody) this.code(thenBody).endIf(); - else if (elseBody) throw new Error("CodeGen: \"else\" body without \"then\" body"); - return this; - } - elseIf(condition) { - return this._elseNode(new If(condition)); - } - else() { - return this._elseNode(new Else()); - } - endIf() { - return this._endBlockNode(If, Else); - } - _for(node, forBody) { - this._blockNode(node); - if (forBody) this.code(forBody).endFor(); - return this; - } - for(iteration, forBody) { - return this._for(new ForLoop(iteration), forBody); - } - forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) { - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForRange(varKind, name, from, to), () => forBody(name)); - } - forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) { - const name = this._scope.toName(nameOrPrefix); - if (this.opts.es5) { - const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable); - return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i) => { - this.var(name, (0, code_1._)`${arr}[${i}]`); - forBody(name); - }); - } - return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)); - } - forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) { - if (this.opts.ownProperties) return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody); - const name = this._scope.toName(nameOrPrefix); - return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)); - } - endFor() { - return this._endBlockNode(For); - } - label(label) { - return this._leafNode(new Label(label)); - } - break(label) { - return this._leafNode(new Break(label)); - } - return(value) { - const node = new Return(); - this._blockNode(node); - this.code(value); - if (node.nodes.length !== 1) throw new Error("CodeGen: \"return\" should have one node"); - return this._endBlockNode(Return); - } - try(tryBody, catchCode, finallyCode) { - if (!catchCode && !finallyCode) throw new Error("CodeGen: \"try\" without \"catch\" and \"finally\""); - const node = new Try(); - this._blockNode(node); - this.code(tryBody); - if (catchCode) { - const error = this.name("e"); - this._currNode = node.catch = new Catch(error); - catchCode(error); - } - if (finallyCode) { - this._currNode = node.finally = new Finally(); - this.code(finallyCode); - } - return this._endBlockNode(Catch, Finally); - } - throw(error) { - return this._leafNode(new Throw(error)); - } - block(body, nodeCount) { - this._blockStarts.push(this._nodes.length); - if (body) this.code(body).endBlock(nodeCount); - return this; - } - endBlock(nodeCount) { - const len = this._blockStarts.pop(); - if (len === void 0) throw new Error("CodeGen: not in self-balancing block"); - const toClose = this._nodes.length - len; - if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`); - this._nodes.length = len; - return this; - } - func(name, args = code_1.nil, async, funcBody) { - this._blockNode(new Func(name, args, async)); - if (funcBody) this.code(funcBody).endFunc(); - return this; - } - endFunc() { - return this._endBlockNode(Func); - } - optimize(n = 1) { - while (n-- > 0) { - this._root.optimizeNodes(); - this._root.optimizeNames(this._root.names, this._constants); - } - } - _leafNode(node) { - this._currNode.nodes.push(node); - return this; - } - _blockNode(node) { - this._currNode.nodes.push(node); - this._nodes.push(node); - } - _endBlockNode(N1, N2) { - const n = this._currNode; - if (n instanceof N1 || N2 && n instanceof N2) { - this._nodes.pop(); - return this; - } - throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`); - } - _elseNode(node) { - const n = this._currNode; - if (!(n instanceof If)) throw new Error("CodeGen: \"else\" without \"if\""); - this._currNode = n.else = node; - return this; - } - get _root() { - return this._nodes[0]; - } - get _currNode() { - const ns = this._nodes; - return ns[ns.length - 1]; - } - set _currNode(node) { - const ns = this._nodes; - ns[ns.length - 1] = node; - } - }; - exports.CodeGen = CodeGen; - function addNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) + (from[n] || 0); - return names; - } - function addExprNames(names, from) { - return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names; - } - function optimizeExpr(expr, names, constants) { - if (expr instanceof code_1.Name) return replaceName(expr); - if (!canOptimize(expr)) return expr; - return new code_1._Code(expr._items.reduce((items, c) => { - if (c instanceof code_1.Name) c = replaceName(c); - if (c instanceof code_1._Code) items.push(...c._items); - else items.push(c); - return items; - }, [])); - function replaceName(n) { - const c = constants[n.str]; - if (c === void 0 || names[n.str] !== 1) return n; - delete names[n.str]; - return c; - } - function canOptimize(e) { - return e instanceof code_1._Code && e._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0); - } - } - function subtractNames(names, from) { - for (const n in from) names[n] = (names[n] || 0) - (from[n] || 0); - } - function not(x) { - return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`; - } - exports.not = not; - const andCode = mappend(exports.operators.AND); - function and(...args) { - return args.reduce(andCode); - } - exports.and = and; - const orCode = mappend(exports.operators.OR); - function or(...args) { - return args.reduce(orCode); - } - exports.or = or; - function mappend(op) { - return (x, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`; - } - function par(x) { - return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/util.js -var require_util = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0; - const codegen_1 = require_codegen(); - const code_1 = require_code$1(); - function toHash(arr) { - const hash = {}; - for (const item of arr) hash[item] = true; - return hash; - } - exports.toHash = toHash; - function alwaysValidSchema(it, schema) { - if (typeof schema == "boolean") return schema; - if (Object.keys(schema).length === 0) return true; - checkUnknownRules(it, schema); - return !schemaHasRules(schema, it.self.RULES.all); - } - exports.alwaysValidSchema = alwaysValidSchema; - function checkUnknownRules(it, schema = it.schema) { - const { opts, self } = it; - if (!opts.strictSchema) return; - if (typeof schema === "boolean") return; - const rules = self.RULES.keywords; - for (const key in schema) if (!rules[key]) checkStrictMode(it, `unknown keyword: "${key}"`); - } - exports.checkUnknownRules = checkUnknownRules; - function schemaHasRules(schema, rules) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (rules[key]) return true; - return false; - } - exports.schemaHasRules = schemaHasRules; - function schemaHasRulesButRef(schema, RULES) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (key !== "$ref" && RULES.all[key]) return true; - return false; - } - exports.schemaHasRulesButRef = schemaHasRulesButRef; - function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) { - if (!$data) { - if (typeof schema == "number" || typeof schema == "boolean") return schema; - if (typeof schema == "string") return (0, codegen_1._)`${schema}`; - } - return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`; - } - exports.schemaRefOrVal = schemaRefOrVal; - function unescapeFragment(str) { - return unescapeJsonPointer(decodeURIComponent(str)); - } - exports.unescapeFragment = unescapeFragment; - function escapeFragment(str) { - return encodeURIComponent(escapeJsonPointer(str)); - } - exports.escapeFragment = escapeFragment; - function escapeJsonPointer(str) { - if (typeof str == "number") return `${str}`; - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } - exports.escapeJsonPointer = escapeJsonPointer; - function unescapeJsonPointer(str) { - return str.replace(/~1/g, "/").replace(/~0/g, "~"); - } - exports.unescapeJsonPointer = unescapeJsonPointer; - function eachItem(xs, f) { - if (Array.isArray(xs)) for (const x of xs) f(x); - else f(xs); - } - exports.eachItem = eachItem; - function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues, resultToName }) { - return (gen, from, to, toName) => { - const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues(from, to); - return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res; - }; - } - exports.mergeEvaluated = { - props: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => { - gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`)); - }), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => { - if (from === true) gen.assign(to, true); - else { - gen.assign(to, (0, codegen_1._)`${to} || {}`); - setEvaluated(gen, to, from); - } - }), - mergeValues: (from, to) => from === true ? true : { - ...from, - ...to - }, - resultToName: evaluatedPropsToName - }), - items: makeMergeEvaluated({ - mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)), - mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)), - mergeValues: (from, to) => from === true ? true : Math.max(from, to), - resultToName: (gen, items) => gen.var("items", items) - }) - }; - function evaluatedPropsToName(gen, ps) { - if (ps === true) return gen.var("props", true); - const props = gen.var("props", (0, codegen_1._)`{}`); - if (ps !== void 0) setEvaluated(gen, props, ps); - return props; - } - exports.evaluatedPropsToName = evaluatedPropsToName; - function setEvaluated(gen, props, ps) { - Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true)); - } - exports.setEvaluated = setEvaluated; - const snippets = {}; - function useFunc(gen, f) { - return gen.scopeValue("func", { - ref: f, - code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.code)) - }); - } - exports.useFunc = useFunc; - var Type; - (function(Type) { - Type[Type["Num"] = 0] = "Num"; - Type[Type["Str"] = 1] = "Str"; - })(Type || (exports.Type = Type = {})); - function getErrorPath(dataProp, dataPropType, jsPropertySyntax) { - if (dataProp instanceof codegen_1.Name) { - const isNumber = dataPropType === Type.Num; - return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`; - } - return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp); - } - exports.getErrorPath = getErrorPath; - function checkStrictMode(it, msg, mode = it.opts.strictSchema) { - if (!mode) return; - msg = `strict mode: ${msg}`; - if (mode === true) throw new Error(msg); - it.self.logger.warn(msg); - } - exports.checkStrictMode = checkStrictMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/names.js -var require_names = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const names = { - data: new codegen_1.Name("data"), - valCxt: new codegen_1.Name("valCxt"), - instancePath: new codegen_1.Name("instancePath"), - parentData: new codegen_1.Name("parentData"), - parentDataProperty: new codegen_1.Name("parentDataProperty"), - rootData: new codegen_1.Name("rootData"), - dynamicAnchors: new codegen_1.Name("dynamicAnchors"), - vErrors: new codegen_1.Name("vErrors"), - errors: new codegen_1.Name("errors"), - this: new codegen_1.Name("this"), - self: new codegen_1.Name("self"), - scope: new codegen_1.Name("scope"), - json: new codegen_1.Name("json"), - jsonPos: new codegen_1.Name("jsonPos"), - jsonLen: new codegen_1.Name("jsonLen"), - jsonPart: new codegen_1.Name("jsonPart") - }; - exports.default = names; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/errors.js -var require_errors = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - exports.keywordError = { message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation` }; - exports.keyword$DataError = { message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)` }; - function reportError(cxt, error = exports.keywordError, errorPaths, overrideAllErrors) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - const errObj = errorObjectCode(cxt, error, errorPaths); - if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) addError(gen, errObj); - else returnErrors(it, (0, codegen_1._)`[${errObj}]`); - } - exports.reportError = reportError; - function reportExtraError(cxt, error = exports.keywordError, errorPaths) { - const { it } = cxt; - const { gen, compositeRule, allErrors } = it; - addError(gen, errorObjectCode(cxt, error, errorPaths)); - if (!(compositeRule || allErrors)) returnErrors(it, names_1.default.vErrors); - } - exports.reportExtraError = reportExtraError; - function resetErrorsCount(gen, errsCount) { - gen.assign(names_1.default.errors, errsCount); - gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null))); - } - exports.resetErrorsCount = resetErrorsCount; - function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) { - /* istanbul ignore if */ - if (errsCount === void 0) throw new Error("ajv implementation error"); - const err = gen.name("err"); - gen.forRange("i", errsCount, names_1.default.errors, (i) => { - gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`); - gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath))); - gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`); - if (it.opts.verbose) { - gen.assign((0, codegen_1._)`${err}.schema`, schemaValue); - gen.assign((0, codegen_1._)`${err}.data`, data); - } - }); - } - exports.extendErrors = extendErrors; - function addError(gen, errObj) { - const err = gen.const("err", errObj); - gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`); - gen.code((0, codegen_1._)`${names_1.default.errors}++`); - } - function returnErrors(it, errs) { - const { gen, validateName, schemaEnv } = it; - if (schemaEnv.$async) gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, errs); - gen.return(false); - } - } - const E = { - keyword: new codegen_1.Name("keyword"), - schemaPath: new codegen_1.Name("schemaPath"), - params: new codegen_1.Name("params"), - propertyName: new codegen_1.Name("propertyName"), - message: new codegen_1.Name("message"), - schema: new codegen_1.Name("schema"), - parentSchema: new codegen_1.Name("parentSchema") - }; - function errorObjectCode(cxt, error, errorPaths) { - const { createErrors } = cxt.it; - if (createErrors === false) return (0, codegen_1._)`{}`; - return errorObject(cxt, error, errorPaths); - } - function errorObject(cxt, error, errorPaths = {}) { - const { gen, it } = cxt; - const keyValues = [errorInstancePath(it, errorPaths), errorSchemaPath(cxt, errorPaths)]; - extraErrorProps(cxt, error, keyValues); - return gen.object(...keyValues); - } - function errorInstancePath({ errorPath }, { instancePath }) { - const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath; - return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)]; - } - function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) { - let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`; - if (schemaPath) schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`; - return [E.schemaPath, schPath]; - } - function extraErrorProps(cxt, { params, message }, keyValues) { - const { keyword, data, schemaValue, it } = cxt; - const { opts, propertyName, topSchemaRef, schemaPath } = it; - keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]); - if (opts.messages) keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]); - if (opts.verbose) keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]); - if (propertyName) keyValues.push([E.propertyName, propertyName]); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/boolSchema.js -var require_boolSchema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0; - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const boolError = { message: "boolean schema is false" }; - function topBoolOrEmptySchema(it) { - const { gen, schema, validateName } = it; - if (schema === false) falseSchemaError(it, false); - else if (typeof schema == "object" && schema.$async === true) gen.return(names_1.default.data); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, null); - gen.return(true); - } - } - exports.topBoolOrEmptySchema = topBoolOrEmptySchema; - function boolOrEmptySchema(it, valid) { - const { gen, schema } = it; - if (schema === false) { - gen.var(valid, false); - falseSchemaError(it); - } else gen.var(valid, true); - } - exports.boolOrEmptySchema = boolOrEmptySchema; - function falseSchemaError(it, overrideAllErrors) { - const { gen, data } = it; - const cxt = { - gen, - keyword: "false schema", - data, - schema: false, - schemaCode: false, - schemaValue: false, - params: {}, - it - }; - (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/rules.js -var require_rules = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getRules = exports.isJSONType = void 0; - const jsonTypes = new Set([ - "string", - "number", - "integer", - "boolean", - "null", - "object", - "array" - ]); - function isJSONType(x) { - return typeof x == "string" && jsonTypes.has(x); - } - exports.isJSONType = isJSONType; - function getRules() { - const groups = { - number: { - type: "number", - rules: [] - }, - string: { - type: "string", - rules: [] - }, - array: { - type: "array", - rules: [] - }, - object: { - type: "object", - rules: [] - } - }; - return { - types: { - ...groups, - integer: true, - boolean: true, - null: true - }, - rules: [ - { rules: [] }, - groups.number, - groups.string, - groups.array, - groups.object - ], - post: { rules: [] }, - all: {}, - keywords: {} - }; - } - exports.getRules = getRules; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/applicability.js -var require_applicability = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0; - function schemaHasRulesForType({ schema, self }, type) { - const group = self.RULES.types[type]; - return group && group !== true && shouldUseGroup(schema, group); - } - exports.schemaHasRulesForType = schemaHasRulesForType; - function shouldUseGroup(schema, group) { - return group.rules.some((rule) => shouldUseRule(schema, rule)); - } - exports.shouldUseGroup = shouldUseGroup; - function shouldUseRule(schema, rule) { - var _a; - return schema[rule.keyword] !== void 0 || ((_a = rule.definition.implements) === null || _a === void 0 ? void 0 : _a.some((kwd) => schema[kwd] !== void 0)); - } - exports.shouldUseRule = shouldUseRule; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/dataType.js -var require_dataType = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0; - const rules_1 = require_rules(); - const applicability_1 = require_applicability(); - const errors_1 = require_errors(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - var DataType; - (function(DataType) { - DataType[DataType["Correct"] = 0] = "Correct"; - DataType[DataType["Wrong"] = 1] = "Wrong"; - })(DataType || (exports.DataType = DataType = {})); - function getSchemaTypes(schema) { - const types = getJSONTypes(schema.type); - if (types.includes("null")) { - if (schema.nullable === false) throw new Error("type: null contradicts nullable: false"); - } else { - if (!types.length && schema.nullable !== void 0) throw new Error("\"nullable\" cannot be used without \"type\""); - if (schema.nullable === true) types.push("null"); - } - return types; - } - exports.getSchemaTypes = getSchemaTypes; - function getJSONTypes(ts) { - const types = Array.isArray(ts) ? ts : ts ? [ts] : []; - if (types.every(rules_1.isJSONType)) return types; - throw new Error("type must be JSONType or JSONType[]: " + types.join(",")); - } - exports.getJSONTypes = getJSONTypes; - function coerceAndCheckDataType(it, types) { - const { gen, data, opts } = it; - const coerceTo = coerceToTypes(types, opts.coerceTypes); - const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0])); - if (checkTypes) { - const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong); - gen.if(wrongType, () => { - if (coerceTo.length) coerceData(it, types, coerceTo); - else reportTypeError(it); - }); - } - return checkTypes; - } - exports.coerceAndCheckDataType = coerceAndCheckDataType; - const COERCIBLE = new Set([ - "string", - "number", - "integer", - "boolean", - "null" - ]); - function coerceToTypes(types, coerceTypes) { - return coerceTypes ? types.filter((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "array") : []; - } - function coerceData(it, types, coerceTo) { - const { gen, data, opts } = it; - const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`); - const coerced = gen.let("coerced", (0, codegen_1._)`undefined`); - if (opts.coerceTypes === "array") gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data))); - gen.if((0, codegen_1._)`${coerced} !== undefined`); - for (const t of coerceTo) if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") coerceSpecificType(t); - gen.else(); - reportTypeError(it); - gen.endIf(); - gen.if((0, codegen_1._)`${coerced} !== undefined`, () => { - gen.assign(data, coerced); - assignParentData(it, coerced); - }); - function coerceSpecificType(t) { - switch (t) { - case "string": - gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`); - return; - case "number": - gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null - || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "integer": - gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null - || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`); - return; - case "boolean": - gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true); - return; - case "null": - gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`); - gen.assign(coerced, null); - return; - case "array": gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number" - || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`); - } - } - } - function assignParentData({ gen, parentData, parentDataProperty }, expr) { - gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr)); - } - function checkDataType(dataType, data, strictNums, correct = DataType.Correct) { - const EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ; - let cond; - switch (dataType) { - case "null": return (0, codegen_1._)`${data} ${EQ} null`; - case "array": - cond = (0, codegen_1._)`Array.isArray(${data})`; - break; - case "object": - cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`; - break; - case "integer": - cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`); - break; - case "number": - cond = numCond(); - break; - default: return (0, codegen_1._)`typeof ${data} ${EQ} ${dataType}`; - } - return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond); - function numCond(_cond = codegen_1.nil) { - return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil); - } - } - exports.checkDataType = checkDataType; - function checkDataTypes(dataTypes, data, strictNums, correct) { - if (dataTypes.length === 1) return checkDataType(dataTypes[0], data, strictNums, correct); - let cond; - const types = (0, util_1.toHash)(dataTypes); - if (types.array && types.object) { - const notObj = (0, codegen_1._)`typeof ${data} != "object"`; - cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`; - delete types.null; - delete types.array; - delete types.object; - } else cond = codegen_1.nil; - if (types.number) delete types.integer; - for (const t in types) cond = (0, codegen_1.and)(cond, checkDataType(t, data, strictNums, correct)); - return cond; - } - exports.checkDataTypes = checkDataTypes; - const typeError = { - message: ({ schema }) => `must be ${schema}`, - params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}` - }; - function reportTypeError(it) { - const cxt = getTypeErrorContext(it); - (0, errors_1.reportError)(cxt, typeError); - } - exports.reportTypeError = reportTypeError; - function getTypeErrorContext(it) { - const { gen, data, schema } = it; - const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type"); - return { - gen, - keyword: "type", - data, - schema: schema.type, - schemaCode, - schemaValue: schemaCode, - parentSchema: schema, - params: {}, - it - }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/defaults.js -var require_defaults = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.assignDefaults = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function assignDefaults(it, ty) { - const { properties, items } = it.schema; - if (ty === "object" && properties) for (const key in properties) assignDefault(it, key, properties[key].default); - else if (ty === "array" && Array.isArray(items)) items.forEach((sch, i) => assignDefault(it, i, sch.default)); - } - exports.assignDefaults = assignDefaults; - function assignDefault(it, prop, defaultValue) { - const { gen, compositeRule, data, opts } = it; - if (defaultValue === void 0) return; - const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`; - if (compositeRule) { - (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`); - return; - } - let condition = (0, codegen_1._)`${childData} === undefined`; - if (opts.useDefaults === "empty") condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`; - gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/code.js -var require_code = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const util_2 = require_util(); - function checkReportMissingProp(cxt, prop) { - const { gen, data, it } = cxt; - gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => { - cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true); - cxt.error(); - }); - } - exports.checkReportMissingProp = checkReportMissingProp; - function checkMissingProp({ gen, data, it: { opts } }, properties, missing) { - return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`))); - } - exports.checkMissingProp = checkMissingProp; - function reportMissingProp(cxt, missing) { - cxt.setParams({ missingProperty: missing }, true); - cxt.error(); - } - exports.reportMissingProp = reportMissingProp; - function hasPropFunc(gen) { - return gen.scopeValue("func", { - ref: Object.prototype.hasOwnProperty, - code: (0, codegen_1._)`Object.prototype.hasOwnProperty` - }); - } - exports.hasPropFunc = hasPropFunc; - function isOwnProperty(gen, data, property) { - return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`; - } - exports.isOwnProperty = isOwnProperty; - function propertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`; - return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond; - } - exports.propertyInData = propertyInData; - function noPropertyInData(gen, data, property, ownProperties) { - const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`; - return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond; - } - exports.noPropertyInData = noPropertyInData; - function allSchemaProperties(schemaMap) { - return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []; - } - exports.allSchemaProperties = allSchemaProperties; - function schemaProperties(it, schemaMap) { - return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p])); - } - exports.schemaProperties = schemaProperties; - function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) { - const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data; - const valCxt = [ - [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)], - [names_1.default.parentData, it.parentData], - [names_1.default.parentDataProperty, it.parentDataProperty], - [names_1.default.rootData, names_1.default.rootData] - ]; - if (it.opts.dynamicRef) valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]); - const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`; - return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`; - } - exports.callValidateCode = callValidateCode; - const newRegExp = (0, codegen_1._)`new RegExp`; - function usePattern({ gen, it: { opts } }, pattern) { - const u = opts.unicodeRegExp ? "u" : ""; - const { regExp } = opts.code; - const rx = regExp(pattern, u); - return gen.scopeValue("pattern", { - key: rx.toString(), - ref: rx, - code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})` - }); - } - exports.usePattern = usePattern; - function validateArray(cxt) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - if (it.allErrors) { - const validArr = gen.let("valid", true); - validateItems(() => gen.assign(validArr, false)); - return validArr; - } - gen.var(valid, true); - validateItems(() => gen.break()); - return valid; - function validateItems(notValid) { - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - gen.if((0, codegen_1.not)(valid), notValid); - }); - } - } - exports.validateArray = validateArray; - function validateUnion(cxt) { - const { gen, schema, keyword, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch)) && !it.opts.unevaluated) return; - const valid = gen.let("valid", false); - const schValid = gen.name("_valid"); - gen.block(() => schema.forEach((_sch, i) => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: i, - compositeRule: true - }, schValid); - gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`); - if (!cxt.mergeValidEvaluated(schCxt, schValid)) gen.if((0, codegen_1.not)(valid)); - })); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - } - exports.validateUnion = validateUnion; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/keyword.js -var require_keyword = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const code_1 = require_code(); - const errors_1 = require_errors(); - function macroKeywordCode(cxt, def) { - const { gen, keyword, schema, parentSchema, it } = cxt; - const macroSchema = def.macro.call(it.self, schema, parentSchema, it); - const schemaRef = useKeyword(gen, keyword, macroSchema); - if (it.opts.validateSchema !== false) it.self.validateSchema(macroSchema, true); - const valid = gen.name("valid"); - cxt.subschema({ - schema: macroSchema, - schemaPath: codegen_1.nil, - errSchemaPath: `${it.errSchemaPath}/${keyword}`, - topSchemaRef: schemaRef, - compositeRule: true - }, valid); - cxt.pass(valid, () => cxt.error(true)); - } - exports.macroKeywordCode = macroKeywordCode; - function funcKeywordCode(cxt, def) { - var _a; - const { gen, keyword, schema, parentSchema, $data, it } = cxt; - checkAsyncKeyword(it, def); - const validateRef = useKeyword(gen, keyword, !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate); - const valid = gen.let("valid"); - cxt.block$data(valid, validateKeyword); - cxt.ok((_a = def.valid) !== null && _a !== void 0 ? _a : valid); - function validateKeyword() { - if (def.errors === false) { - assignValid(); - if (def.modifying) modifyData(cxt); - reportErrs(() => cxt.error()); - } else { - const ruleErrs = def.async ? validateAsync() : validateSync(); - if (def.modifying) modifyData(cxt); - reportErrs(() => addErrs(cxt, ruleErrs)); - } - } - function validateAsync() { - const ruleErrs = gen.let("ruleErrs", null); - gen.try(() => assignValid((0, codegen_1._)`await `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e))); - return ruleErrs; - } - function validateSync() { - const validateErrs = (0, codegen_1._)`${validateRef}.errors`; - gen.assign(validateErrs, null); - assignValid(codegen_1.nil); - return validateErrs; - } - function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) { - const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self; - const passSchema = !("compile" in def && !$data || def.schema === false); - gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying); - } - function reportErrs(errors) { - var _a$1; - gen.if((0, codegen_1.not)((_a$1 = def.valid) !== null && _a$1 !== void 0 ? _a$1 : valid), errors); - } - } - exports.funcKeywordCode = funcKeywordCode; - function modifyData(cxt) { - const { gen, data, it } = cxt; - gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`)); - } - function addErrs(cxt, errs) { - const { gen } = cxt; - gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => { - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - (0, errors_1.extendErrors)(cxt); - }, () => cxt.error()); - } - function checkAsyncKeyword({ schemaEnv }, def) { - if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema"); - } - function useKeyword(gen, keyword, result) { - if (result === void 0) throw new Error(`keyword "${keyword}" failed to compile`); - return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { - ref: result, - code: (0, codegen_1.stringify)(result) - }); - } - function validSchemaType(schema, schemaType, allowUndefined = false) { - return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined"); - } - exports.validSchemaType = validSchemaType; - function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) { - /* istanbul ignore if */ - if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) throw new Error("ajv implementation error"); - const deps = def.dependencies; - if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`); - if (def.validateSchema) { - if (!def.validateSchema(schema[keyword])) { - const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self.errorsText(def.validateSchema.errors); - if (opts.validateSchema === "log") self.logger.error(msg); - else throw new Error(msg); - } - } - } - exports.validateKeywordUsage = validateKeywordUsage; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/subschema.js -var require_subschema = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) { - if (keyword !== void 0 && schema !== void 0) throw new Error("both \"keyword\" and \"schema\" passed, only one allowed"); - if (keyword !== void 0) { - const sch = it.schema[keyword]; - return schemaProp === void 0 ? { - schema: sch, - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}` - } : { - schema: sch[schemaProp], - schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`, - errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}` - }; - } - if (schema !== void 0) { - if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) throw new Error("\"schemaPath\", \"errSchemaPath\" and \"topSchemaRef\" are required with \"schema\""); - return { - schema, - schemaPath, - topSchemaRef, - errSchemaPath - }; - } - throw new Error("either \"keyword\" or \"schema\" must be passed"); - } - exports.getSubschema = getSubschema; - function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) { - if (data !== void 0 && dataProp !== void 0) throw new Error("both \"data\" and \"dataProp\" passed, only one allowed"); - const { gen } = it; - if (dataProp !== void 0) { - const { errorPath, dataPathArr, opts } = it; - dataContextProps(gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true)); - subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`; - subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`; - subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty]; - } - if (data !== void 0) { - dataContextProps(data instanceof codegen_1.Name ? data : gen.let("data", data, true)); - if (propertyName !== void 0) subschema.propertyName = propertyName; - } - if (dataTypes) subschema.dataTypes = dataTypes; - function dataContextProps(_nextData) { - subschema.data = _nextData; - subschema.dataLevel = it.dataLevel + 1; - subschema.dataTypes = []; - it.definedProperties = /* @__PURE__ */ new Set(); - subschema.parentData = it.data; - subschema.dataNames = [...it.dataNames, _nextData]; - } - } - exports.extendSubschemaData = extendSubschemaData; - function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) { - if (compositeRule !== void 0) subschema.compositeRule = compositeRule; - if (createErrors !== void 0) subschema.createErrors = createErrors; - if (allErrors !== void 0) subschema.allErrors = allErrors; - subschema.jtdDiscriminator = jtdDiscriminator; - subschema.jtdMetadata = jtdMetadata; - } - exports.extendSubschemaMode = extendSubschemaMode; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js -var require_fast_deep_equal = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length, i, keys; - if (Array.isArray(a)) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length; i-- !== 0;) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/json-schema-traverse@1.0.0/node_modules/json-schema-traverse/index.js -var require_json_schema_traverse = /* @__PURE__ */ __commonJSMin(((exports, module) => { - var traverse = module.exports = function(schema, opts, cb) { - if (typeof opts == "function") { - cb = opts; - opts = {}; - } - cb = opts.cb || cb; - var pre = typeof cb == "function" ? cb : cb.pre || function() {}; - var post = cb.post || function() {}; - _traverse(opts, pre, post, schema, "", schema); - }; - traverse.keywords = { - additionalItems: true, - items: true, - contains: true, - additionalProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true - }; - traverse.arrayKeywords = { - items: true, - allOf: true, - anyOf: true, - oneOf: true - }; - traverse.propsKeywords = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependencies: true - }; - traverse.skipKeywords = { - default: true, - enum: true, - const: true, - required: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true - }; - function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) { - if (schema && typeof schema == "object" && !Array.isArray(schema)) { - pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - for (var key in schema) { - var sch = schema[key]; - if (Array.isArray(sch)) { - if (key in traverse.arrayKeywords) for (var i = 0; i < sch.length; i++) _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i); - } else if (key in traverse.propsKeywords) { - if (sch && typeof sch == "object") for (var prop in sch) _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop); - } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema); - } - post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex); - } - } - function escapeJsonPtr(str) { - return str.replace(/~/g, "~0").replace(/\//g, "~1"); - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/resolve.js -var require_resolve = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0; - const util_1 = require_util(); - const equal = require_fast_deep_equal(); - const traverse = require_json_schema_traverse(); - const SIMPLE_INLINED = new Set([ - "type", - "format", - "pattern", - "maxLength", - "minLength", - "maxProperties", - "minProperties", - "maxItems", - "minItems", - "maximum", - "minimum", - "uniqueItems", - "multipleOf", - "required", - "enum", - "const" - ]); - function inlineRef(schema, limit = true) { - if (typeof schema == "boolean") return true; - if (limit === true) return !hasRef(schema); - if (!limit) return false; - return countKeys(schema) <= limit; - } - exports.inlineRef = inlineRef; - const REF_KEYWORDS = new Set([ - "$ref", - "$recursiveRef", - "$recursiveAnchor", - "$dynamicRef", - "$dynamicAnchor" - ]); - function hasRef(schema) { - for (const key in schema) { - if (REF_KEYWORDS.has(key)) return true; - const sch = schema[key]; - if (Array.isArray(sch) && sch.some(hasRef)) return true; - if (typeof sch == "object" && hasRef(sch)) return true; - } - return false; - } - function countKeys(schema) { - let count = 0; - for (const key in schema) { - if (key === "$ref") return Infinity; - count++; - if (SIMPLE_INLINED.has(key)) continue; - if (typeof schema[key] == "object") (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch)); - if (count === Infinity) return Infinity; - } - return count; - } - function getFullPath(resolver, id = "", normalize) { - if (normalize !== false) id = normalizeId(id); - return _getFullPath(resolver, resolver.parse(id)); - } - exports.getFullPath = getFullPath; - function _getFullPath(resolver, p) { - return resolver.serialize(p).split("#")[0] + "#"; - } - exports._getFullPath = _getFullPath; - const TRAILING_SLASH_HASH = /#\/?$/; - function normalizeId(id) { - return id ? id.replace(TRAILING_SLASH_HASH, "") : ""; - } - exports.normalizeId = normalizeId; - function resolveUrl(resolver, baseId, id) { - id = normalizeId(id); - return resolver.resolve(baseId, id); - } - exports.resolveUrl = resolveUrl; - const ANCHOR = /^[a-z_][-a-z0-9._]*$/i; - function getSchemaRefs(schema, baseId) { - if (typeof schema == "boolean") return {}; - const { schemaId, uriResolver } = this.opts; - const schId = normalizeId(schema[schemaId] || baseId); - const baseIds = { "": schId }; - const pathPrefix = getFullPath(uriResolver, schId, false); - const localRefs = {}; - const schemaRefs = /* @__PURE__ */ new Set(); - traverse(schema, { allKeys: true }, (sch, jsonPtr, _, parentJsonPtr) => { - if (parentJsonPtr === void 0) return; - const fullPath = pathPrefix + jsonPtr; - let innerBaseId = baseIds[parentJsonPtr]; - if (typeof sch[schemaId] == "string") innerBaseId = addRef.call(this, sch[schemaId]); - addAnchor.call(this, sch.$anchor); - addAnchor.call(this, sch.$dynamicAnchor); - baseIds[jsonPtr] = innerBaseId; - function addRef(ref) { - const _resolve = this.opts.uriResolver.resolve; - ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref); - if (schemaRefs.has(ref)) throw ambiguos(ref); - schemaRefs.add(ref); - let schOrRef = this.refs[ref]; - if (typeof schOrRef == "string") schOrRef = this.refs[schOrRef]; - if (typeof schOrRef == "object") checkAmbiguosRef(sch, schOrRef.schema, ref); - else if (ref !== normalizeId(fullPath)) if (ref[0] === "#") { - checkAmbiguosRef(sch, localRefs[ref], ref); - localRefs[ref] = sch; - } else this.refs[ref] = fullPath; - return ref; - } - function addAnchor(anchor) { - if (typeof anchor == "string") { - if (!ANCHOR.test(anchor)) throw new Error(`invalid anchor "${anchor}"`); - addRef.call(this, `#${anchor}`); - } - } - }); - return localRefs; - function checkAmbiguosRef(sch1, sch2, ref) { - if (sch2 !== void 0 && !equal(sch1, sch2)) throw ambiguos(ref); - } - function ambiguos(ref) { - return /* @__PURE__ */ new Error(`reference "${ref}" resolves to more than one schema`); - } - } - exports.getSchemaRefs = getSchemaRefs; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/validate/index.js -var require_validate = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0; - const boolSchema_1 = require_boolSchema(); - const dataType_1 = require_dataType(); - const applicability_1 = require_applicability(); - const dataType_2 = require_dataType(); - const defaults_1 = require_defaults(); - const keyword_1 = require_keyword(); - const subschema_1 = require_subschema(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const errors_1 = require_errors(); - function validateFunctionCode(it) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - topSchemaObjCode(it); - return; - } - } - validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it)); - } - exports.validateFunctionCode = validateFunctionCode; - function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) { - if (opts.code.es5) gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => { - gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`); - destructureValCxtES5(gen, opts); - gen.code(body); - }); - else gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body)); - } - function destructureValCxt(opts) { - return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`; - } - function destructureValCxtES5(gen, opts) { - gen.if(names_1.default.valCxt, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`); - gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`); - gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`); - }, () => { - gen.var(names_1.default.instancePath, (0, codegen_1._)`""`); - gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`); - gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`); - gen.var(names_1.default.rootData, names_1.default.data); - if (opts.dynamicRef) gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`); - }); - } - function topSchemaObjCode(it) { - const { schema, opts, gen } = it; - validateFunction(it, () => { - if (opts.$comment && schema.$comment) commentKeyword(it); - checkNoDefault(it); - gen.let(names_1.default.vErrors, null); - gen.let(names_1.default.errors, 0); - if (opts.unevaluated) resetEvaluated(it); - typeAndKeywords(it); - returnResults(it); - }); - } - function resetEvaluated(it) { - const { gen, validateName } = it; - it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`)); - gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`)); - } - function funcSourceUrl(schema, opts) { - const schId = typeof schema == "object" && schema[opts.schemaId]; - return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil; - } - function subschemaCode(it, valid) { - if (isSchemaObj(it)) { - checkKeywords(it); - if (schemaCxtHasRules(it)) { - subSchemaObjCode(it, valid); - return; - } - } - (0, boolSchema_1.boolOrEmptySchema)(it, valid); - } - function schemaCxtHasRules({ schema, self }) { - if (typeof schema == "boolean") return !schema; - for (const key in schema) if (self.RULES.all[key]) return true; - return false; - } - function isSchemaObj(it) { - return typeof it.schema != "boolean"; - } - function subSchemaObjCode(it, valid) { - const { schema, gen, opts } = it; - if (opts.$comment && schema.$comment) commentKeyword(it); - updateContext(it); - checkAsyncSchema(it); - const errsCount = gen.const("_errs", names_1.default.errors); - typeAndKeywords(it, errsCount); - gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - } - function checkKeywords(it) { - (0, util_1.checkUnknownRules)(it); - checkRefsAndKeywords(it); - } - function typeAndKeywords(it, errsCount) { - if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount); - const types = (0, dataType_1.getSchemaTypes)(it.schema); - schemaKeywords(it, types, !(0, dataType_1.coerceAndCheckDataType)(it, types), errsCount); - } - function checkRefsAndKeywords(it) { - const { schema, errSchemaPath, opts, self } = it; - if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`); - } - function checkNoDefault(it) { - const { schema, opts } = it; - if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) (0, util_1.checkStrictMode)(it, "default is ignored in the schema root"); - } - function updateContext(it) { - const schId = it.schema[it.opts.schemaId]; - if (schId) it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId); - } - function checkAsyncSchema(it) { - if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema"); - } - function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) { - const msg = schema.$comment; - if (opts.$comment === true) gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`); - else if (typeof opts.$comment == "function") { - const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`; - const rootName = gen.scopeValue("root", { ref: schemaEnv.root }); - gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`); - } - } - function returnResults(it) { - const { gen, schemaEnv, validateName, ValidationError, opts } = it; - if (schemaEnv.$async) gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`)); - else { - gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors); - if (opts.unevaluated) assignEvaluated(it); - gen.return((0, codegen_1._)`${names_1.default.errors} === 0`); - } - } - function assignEvaluated({ gen, evaluated, props, items }) { - if (props instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.props`, props); - if (items instanceof codegen_1.Name) gen.assign((0, codegen_1._)`${evaluated}.items`, items); - } - function schemaKeywords(it, types, typeErrors, errsCount) { - const { gen, schema, data, allErrors, opts, self } = it; - const { RULES } = self; - if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) { - gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition)); - return; - } - if (!opts.jtd) checkStrictTypes(it, types); - gen.block(() => { - for (const group of RULES.rules) groupKeywords(group); - groupKeywords(RULES.post); - }); - function groupKeywords(group) { - if (!(0, applicability_1.shouldUseGroup)(schema, group)) return; - if (group.type) { - gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers)); - iterateKeywords(it, group); - if (types.length === 1 && types[0] === group.type && typeErrors) { - gen.else(); - (0, dataType_2.reportTypeError)(it); - } - gen.endIf(); - } else iterateKeywords(it, group); - if (!allErrors) gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`); - } - } - function iterateKeywords(it, group) { - const { gen, schema, opts: { useDefaults } } = it; - if (useDefaults) (0, defaults_1.assignDefaults)(it, group.type); - gen.block(() => { - for (const rule of group.rules) if ((0, applicability_1.shouldUseRule)(schema, rule)) keywordCode(it, rule.keyword, rule.definition, group.type); - }); - } - function checkStrictTypes(it, types) { - if (it.schemaEnv.meta || !it.opts.strictTypes) return; - checkContextTypes(it, types); - if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types); - checkKeywordTypes(it, it.dataTypes); - } - function checkContextTypes(it, types) { - if (!types.length) return; - if (!it.dataTypes.length) { - it.dataTypes = types; - return; - } - types.forEach((t) => { - if (!includesType(it.dataTypes, t)) strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`); - }); - narrowSchemaTypes(it, types); - } - function checkMultipleTypes(it, ts) { - if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) strictTypesError(it, "use allowUnionTypes to allow union type keyword"); - } - function checkKeywordTypes(it, ts) { - const rules = it.self.RULES.all; - for (const keyword in rules) { - const rule = rules[keyword]; - if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) { - const { type } = rule.definition; - if (type.length && !type.some((t) => hasApplicableType(ts, t))) strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`); - } - } - } - function hasApplicableType(schTs, kwdT) { - return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer"); - } - function includesType(ts, t) { - return ts.includes(t) || t === "integer" && ts.includes("number"); - } - function narrowSchemaTypes(it, withTypes) { - const ts = []; - for (const t of it.dataTypes) if (includesType(withTypes, t)) ts.push(t); - else if (withTypes.includes("integer") && t === "number") ts.push("integer"); - it.dataTypes = ts; - } - function strictTypesError(it, msg) { - const schemaPath = it.schemaEnv.baseId + it.errSchemaPath; - msg += ` at "${schemaPath}" (strictTypes)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes); - } - var KeywordCxt = class { - constructor(it, def, keyword) { - (0, keyword_1.validateKeywordUsage)(it, def, keyword); - this.gen = it.gen; - this.allErrors = it.allErrors; - this.keyword = keyword; - this.data = it.data; - this.schema = it.schema[keyword]; - this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data; - this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data); - this.schemaType = def.schemaType; - this.parentSchema = it.schema; - this.params = {}; - this.it = it; - this.def = def; - if (this.$data) this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)); - else { - this.schemaCode = this.schemaValue; - if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`); - } - if ("code" in def ? def.trackErrors : def.errors !== false) this.errsCount = it.gen.const("_errs", names_1.default.errors); - } - result(condition, successAction, failAction) { - this.failResult((0, codegen_1.not)(condition), successAction, failAction); - } - failResult(condition, successAction, failAction) { - this.gen.if(condition); - if (failAction) failAction(); - else this.error(); - if (successAction) { - this.gen.else(); - successAction(); - if (this.allErrors) this.gen.endIf(); - } else if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - pass(condition, failAction) { - this.failResult((0, codegen_1.not)(condition), void 0, failAction); - } - fail(condition) { - if (condition === void 0) { - this.error(); - if (!this.allErrors) this.gen.if(false); - return; - } - this.gen.if(condition); - this.error(); - if (this.allErrors) this.gen.endIf(); - else this.gen.else(); - } - fail$data(condition) { - if (!this.$data) return this.fail(condition); - const { schemaCode } = this; - this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`); - } - error(append, errorParams, errorPaths) { - if (errorParams) { - this.setParams(errorParams); - this._error(append, errorPaths); - this.setParams({}); - return; - } - this._error(append, errorPaths); - } - _error(append, errorPaths) { - (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths); - } - $dataError() { - (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError); - } - reset() { - if (this.errsCount === void 0) throw new Error("add \"trackErrors\" to keyword definition"); - (0, errors_1.resetErrorsCount)(this.gen, this.errsCount); - } - ok(cond) { - if (!this.allErrors) this.gen.if(cond); - } - setParams(obj, assign) { - if (assign) Object.assign(this.params, obj); - else this.params = obj; - } - block$data(valid, codeBlock, $dataValid = codegen_1.nil) { - this.gen.block(() => { - this.check$data(valid, $dataValid); - codeBlock(); - }); - } - check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) { - if (!this.$data) return; - const { gen, schemaCode, schemaType, def } = this; - gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid)); - if (valid !== codegen_1.nil) gen.assign(valid, true); - if (schemaType.length || def.validateSchema) { - gen.elseIf(this.invalid$data()); - this.$dataError(); - if (valid !== codegen_1.nil) gen.assign(valid, false); - } - gen.else(); - } - invalid$data() { - const { gen, schemaCode, schemaType, def, it } = this; - return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema()); - function wrong$DataType() { - if (schemaType.length) { - /* istanbul ignore if */ - if (!(schemaCode instanceof codegen_1.Name)) throw new Error("ajv implementation error"); - const st = Array.isArray(schemaType) ? schemaType : [schemaType]; - return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`; - } - return codegen_1.nil; - } - function invalid$DataSchema() { - if (def.validateSchema) { - const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema }); - return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`; - } - return codegen_1.nil; - } - } - subschema(appl, valid) { - const subschema = (0, subschema_1.getSubschema)(this.it, appl); - (0, subschema_1.extendSubschemaData)(subschema, this.it, appl); - (0, subschema_1.extendSubschemaMode)(subschema, appl); - const nextContext = { - ...this.it, - ...subschema, - items: void 0, - props: void 0 - }; - subschemaCode(nextContext, valid); - return nextContext; - } - mergeEvaluated(schemaCxt, toName) { - const { it, gen } = this; - if (!it.opts.unevaluated) return; - if (it.props !== true && schemaCxt.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName); - if (it.items !== true && schemaCxt.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName); - } - mergeValidEvaluated(schemaCxt, valid) { - const { it, gen } = this; - if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { - gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name)); - return true; - } - } - }; - exports.KeywordCxt = KeywordCxt; - function keywordCode(it, keyword, def, ruleType) { - const cxt = new KeywordCxt(it, def, keyword); - if ("code" in def) def.code(cxt, ruleType); - else if (cxt.$data && def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - else if ("macro" in def) (0, keyword_1.macroKeywordCode)(cxt, def); - else if (def.compile || def.validate) (0, keyword_1.funcKeywordCode)(cxt, def); - } - const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/; - const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/; - function getData($data, { dataLevel, dataNames, dataPathArr }) { - let jsonPointer; - let data; - if ($data === "") return names_1.default.rootData; - if ($data[0] === "/") { - if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`); - jsonPointer = $data; - data = names_1.default.rootData; - } else { - const matches = RELATIVE_JSON_POINTER.exec($data); - if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`); - const up = +matches[1]; - jsonPointer = matches[2]; - if (jsonPointer === "#") { - if (up >= dataLevel) throw new Error(errorMsg("property/index", up)); - return dataPathArr[dataLevel - up]; - } - if (up > dataLevel) throw new Error(errorMsg("data", up)); - data = dataNames[dataLevel - up]; - if (!jsonPointer) return data; - } - let expr = data; - const segments = jsonPointer.split("/"); - for (const segment of segments) if (segment) { - data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`; - expr = (0, codegen_1._)`${expr} && ${data}`; - } - return expr; - function errorMsg(pointerType, up) { - return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`; - } - } - exports.getData = getData; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/validation_error.js -var require_validation_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - var ValidationError = class extends Error { - constructor(errors) { - super("validation failed"); - this.errors = errors; - this.ajv = this.validation = true; - } - }; - exports.default = ValidationError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/ref_error.js -var require_ref_error = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const resolve_1 = require_resolve(); - var MissingRefError = class extends Error { - constructor(resolver, baseId, ref, msg) { - super(msg || `can't resolve reference ${ref} from id ${baseId}`); - this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref); - this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef)); - } - }; - exports.default = MissingRefError; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/compile/index.js -var require_compile = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0; - const codegen_1 = require_codegen(); - const validation_error_1 = require_validation_error(); - const names_1 = require_names(); - const resolve_1 = require_resolve(); - const util_1 = require_util(); - const validate_1 = require_validate(); - var SchemaEnv = class { - constructor(env) { - var _a; - this.refs = {}; - this.dynamicAnchors = {}; - let schema; - if (typeof env.schema == "object") schema = env.schema; - this.schema = env.schema; - this.schemaId = env.schemaId; - this.root = env.root || this; - this.baseId = (_a = env.baseId) !== null && _a !== void 0 ? _a : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]); - this.schemaPath = env.schemaPath; - this.localRefs = env.localRefs; - this.meta = env.meta; - this.$async = schema === null || schema === void 0 ? void 0 : schema.$async; - this.refs = {}; - } - }; - exports.SchemaEnv = SchemaEnv; - function compileSchema(sch) { - const _sch = getCompilingSchema.call(this, sch); - if (_sch) return _sch; - const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); - const { es5, lines } = this.opts.code; - const { ownProperties } = this.opts; - const gen = new codegen_1.CodeGen(this.scope, { - es5, - lines, - ownProperties - }); - let _ValidationError; - if (sch.$async) _ValidationError = gen.scopeValue("Error", { - ref: validation_error_1.default, - code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default` - }); - const validateName = gen.scopeName("validate"); - sch.validateName = validateName; - const schemaCxt = { - gen, - allErrors: this.opts.allErrors, - data: names_1.default.data, - parentData: names_1.default.parentData, - parentDataProperty: names_1.default.parentDataProperty, - dataNames: [names_1.default.data], - dataPathArr: [codegen_1.nil], - dataLevel: 0, - dataTypes: [], - definedProperties: /* @__PURE__ */ new Set(), - topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { - ref: sch.schema, - code: (0, codegen_1.stringify)(sch.schema) - } : { ref: sch.schema }), - validateName, - ValidationError: _ValidationError, - schema: sch.schema, - schemaEnv: sch, - rootId, - baseId: sch.baseId || rootId, - schemaPath: codegen_1.nil, - errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), - errorPath: (0, codegen_1._)`""`, - opts: this.opts, - self: this - }; - let sourceCode; - try { - this._compilations.add(sch); - (0, validate_1.validateFunctionCode)(schemaCxt); - gen.optimize(this.opts.code.optimize); - const validateCode = gen.toString(); - sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`; - if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch); - const validate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode)(this, this.scope.get()); - this.scope.value(validateName, { ref: validate }); - validate.errors = null; - validate.schema = sch.schema; - validate.schemaEnv = sch; - if (sch.$async) validate.$async = true; - if (this.opts.code.source === true) validate.source = { - validateName, - validateCode, - scopeValues: gen._values - }; - if (this.opts.unevaluated) { - const { props, items } = schemaCxt; - validate.evaluated = { - props: props instanceof codegen_1.Name ? void 0 : props, - items: items instanceof codegen_1.Name ? void 0 : items, - dynamicProps: props instanceof codegen_1.Name, - dynamicItems: items instanceof codegen_1.Name - }; - if (validate.source) validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated); - } - sch.validate = validate; - return sch; - } catch (e) { - delete sch.validate; - delete sch.validateName; - if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode); - throw e; - } finally { - this._compilations.delete(sch); - } - } - exports.compileSchema = compileSchema; - function resolveRef(root, baseId, ref) { - var _a; - ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref); - const schOrFunc = root.refs[ref]; - if (schOrFunc) return schOrFunc; - let _sch = resolve.call(this, root, ref); - if (_sch === void 0) { - const schema = (_a = root.localRefs) === null || _a === void 0 ? void 0 : _a[ref]; - const { schemaId } = this.opts; - if (schema) _sch = new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - if (_sch === void 0) return; - return root.refs[ref] = inlineOrCompile.call(this, _sch); - } - exports.resolveRef = resolveRef; - function inlineOrCompile(sch) { - if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs)) return sch.schema; - return sch.validate ? sch : compileSchema.call(this, sch); - } - function getCompilingSchema(schEnv) { - for (const sch of this._compilations) if (sameSchemaEnv(sch, schEnv)) return sch; - } - exports.getCompilingSchema = getCompilingSchema; - function sameSchemaEnv(s1, s2) { - return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId; - } - function resolve(root, ref) { - let sch; - while (typeof (sch = this.refs[ref]) == "string") ref = sch; - return sch || this.schemas[ref] || resolveSchema.call(this, root, ref); - } - function resolveSchema(root, ref) { - const p = this.opts.uriResolver.parse(ref); - const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p); - let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0); - if (Object.keys(root.schema).length > 0 && refPath === baseId) return getJsonPointer.call(this, p, root); - const id = (0, resolve_1.normalizeId)(refPath); - const schOrRef = this.refs[id] || this.schemas[id]; - if (typeof schOrRef == "string") { - const sch = resolveSchema.call(this, root, schOrRef); - if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object") return; - return getJsonPointer.call(this, p, sch); - } - if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object") return; - if (!schOrRef.validate) compileSchema.call(this, schOrRef); - if (id === (0, resolve_1.normalizeId)(ref)) { - const { schema } = schOrRef; - const { schemaId } = this.opts; - const schId = schema[schemaId]; - if (schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - return new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - } - return getJsonPointer.call(this, p, schOrRef); - } - exports.resolveSchema = resolveSchema; - const PREVENT_SCOPE_CHANGE = new Set([ - "properties", - "patternProperties", - "enum", - "dependencies", - "definitions" - ]); - function getJsonPointer(parsedRef, { baseId, schema, root }) { - var _a; - if (((_a = parsedRef.fragment) === null || _a === void 0 ? void 0 : _a[0]) !== "/") return; - for (const part of parsedRef.fragment.slice(1).split("/")) { - if (typeof schema === "boolean") return; - const partSchema = schema[(0, util_1.unescapeFragment)(part)]; - if (partSchema === void 0) return; - schema = partSchema; - const schId = typeof schema === "object" && schema[this.opts.schemaId]; - if (!PREVENT_SCOPE_CHANGE.has(part) && schId) baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId); - } - let env; - if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) { - const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref); - env = resolveSchema.call(this, root, $ref); - } - const { schemaId } = this.opts; - env = env || new SchemaEnv({ - schema, - schemaId, - root, - baseId - }); - if (env.schema !== env.root.schema) return env; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/data.json -var require_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$id": "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#", - "description": "Meta-schema for $data reference (JSON AnySchema extension proposal)", - "type": "object", - "required": ["$data"], - "properties": { "$data": { - "type": "string", - "anyOf": [{ "format": "relative-json-pointer" }, { "format": "json-pointer" }] - } }, - "additionalProperties": false - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/utils.js -var require_utils = /* @__PURE__ */ __commonJSMin(((exports, module) => { - /** @type {(value: string) => boolean} */ - const isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu); - /** @type {(value: string) => boolean} */ - const isIPv4 = RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u); - /** - * @param {Array} input - * @returns {string} - */ - function stringArrayToHexStripped(input) { - let acc = ""; - let code = 0; - let i = 0; - for (i = 0; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (code === 48) continue; - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - break; - } - for (i += 1; i < input.length; i++) { - code = input[i].charCodeAt(0); - if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) return ""; - acc += input[i]; - } - return acc; - } - /** - * @typedef {Object} GetIPV6Result - * @property {boolean} error - Indicates if there was an error parsing the IPv6 address. - * @property {string} address - The parsed IPv6 address. - * @property {string} [zone] - The zone identifier, if present. - */ - /** - * @param {string} value - * @returns {boolean} - */ - const nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u); - /** - * @param {Array} buffer - * @returns {boolean} - */ - function consumeIsZone(buffer) { - buffer.length = 0; - return true; - } - /** - * @param {Array} buffer - * @param {Array} address - * @param {GetIPV6Result} output - * @returns {boolean} - */ - function consumeHextets(buffer, address, output) { - if (buffer.length) { - const hex = stringArrayToHexStripped(buffer); - if (hex !== "") address.push(hex); - else { - output.error = true; - return false; - } - buffer.length = 0; - } - return true; - } - /** - * @param {string} input - * @returns {GetIPV6Result} - */ - function getIPV6(input) { - let tokenCount = 0; - const output = { - error: false, - address: "", - zone: "" - }; - /** @type {Array} */ - const address = []; - /** @type {Array} */ - const buffer = []; - let endipv6Encountered = false; - let endIpv6 = false; - let consume = consumeHextets; - for (let i = 0; i < input.length; i++) { - const cursor = input[i]; - if (cursor === "[" || cursor === "]") continue; - if (cursor === ":") { - if (endipv6Encountered === true) endIpv6 = true; - if (!consume(buffer, address, output)) break; - if (++tokenCount > 7) { - output.error = true; - break; - } - if (i > 0 && input[i - 1] === ":") endipv6Encountered = true; - address.push(":"); - continue; - } else if (cursor === "%") { - if (!consume(buffer, address, output)) break; - consume = consumeIsZone; - } else { - buffer.push(cursor); - continue; - } - } - if (buffer.length) if (consume === consumeIsZone) output.zone = buffer.join(""); - else if (endIpv6) address.push(buffer.join("")); - else address.push(stringArrayToHexStripped(buffer)); - output.address = address.join(""); - return output; - } - /** - * @typedef {Object} NormalizeIPv6Result - * @property {string} host - The normalized host. - * @property {string} [escapedHost] - The escaped host. - * @property {boolean} isIPV6 - Indicates if the host is an IPv6 address. - */ - /** - * @param {string} host - * @returns {NormalizeIPv6Result} - */ - function normalizeIPv6(host) { - if (findToken(host, ":") < 2) return { - host, - isIPV6: false - }; - const ipv6 = getIPV6(host); - if (!ipv6.error) { - let newHost = ipv6.address; - let escapedHost = ipv6.address; - if (ipv6.zone) { - newHost += "%" + ipv6.zone; - escapedHost += "%25" + ipv6.zone; - } - return { - host: newHost, - isIPV6: true, - escapedHost - }; - } else return { - host, - isIPV6: false - }; - } - /** - * @param {string} str - * @param {string} token - * @returns {number} - */ - function findToken(str, token) { - let ind = 0; - for (let i = 0; i < str.length; i++) if (str[i] === token) ind++; - return ind; - } - /** - * @param {string} path - * @returns {string} - * - * @see https://datatracker.ietf.org/doc/html/rfc3986#section-5.2.4 - */ - function removeDotSegments(path) { - let input = path; - const output = []; - let nextSlash = -1; - let len = 0; - while (len = input.length) { - if (len === 1) if (input === ".") break; - else if (input === "/") { - output.push("/"); - break; - } else { - output.push(input); - break; - } - else if (len === 2) { - if (input[0] === ".") { - if (input[1] === ".") break; - else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === "." || input[1] === "/") { - output.push("/"); - break; - } - } - } else if (len === 3) { - if (input === "/..") { - if (output.length !== 0) output.pop(); - output.push("/"); - break; - } - } - if (input[0] === ".") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(3); - continue; - } - } else if (input[1] === "/") { - input = input.slice(2); - continue; - } - } else if (input[0] === "/") { - if (input[1] === ".") { - if (input[2] === "/") { - input = input.slice(2); - continue; - } else if (input[2] === ".") { - if (input[3] === "/") { - input = input.slice(3); - if (output.length !== 0) output.pop(); - continue; - } - } - } - } - if ((nextSlash = input.indexOf("/", 1)) === -1) { - output.push(input); - break; - } else { - output.push(input.slice(0, nextSlash)); - input = input.slice(nextSlash); - } - } - return output.join(""); - } - /** - * @param {import('../types/index').URIComponent} component - * @param {boolean} esc - * @returns {import('../types/index').URIComponent} - */ - function normalizeComponentEncoding(component, esc) { - const func = esc !== true ? escape : unescape; - if (component.scheme !== void 0) component.scheme = func(component.scheme); - if (component.userinfo !== void 0) component.userinfo = func(component.userinfo); - if (component.host !== void 0) component.host = func(component.host); - if (component.path !== void 0) component.path = func(component.path); - if (component.query !== void 0) component.query = func(component.query); - if (component.fragment !== void 0) component.fragment = func(component.fragment); - return component; - } - /** - * @param {import('../types/index').URIComponent} component - * @returns {string|undefined} - */ - function recomposeAuthority(component) { - const uriTokens = []; - if (component.userinfo !== void 0) { - uriTokens.push(component.userinfo); - uriTokens.push("@"); - } - if (component.host !== void 0) { - let host = unescape(component.host); - if (!isIPv4(host)) { - const ipV6res = normalizeIPv6(host); - if (ipV6res.isIPV6 === true) host = `[${ipV6res.escapedHost}]`; - else host = component.host; - } - uriTokens.push(host); - } - if (typeof component.port === "number" || typeof component.port === "string") { - uriTokens.push(":"); - uriTokens.push(String(component.port)); - } - return uriTokens.length ? uriTokens.join("") : void 0; - } - module.exports = { - nonSimpleDomain, - recomposeAuthority, - normalizeComponentEncoding, - removeDotSegments, - isIPv4, - isUUID, - normalizeIPv6, - stringArrayToHexStripped - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/lib/schemes.js -var require_schemes = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { isUUID } = require_utils(); - const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu; - const supportedSchemeNames = [ - "http", - "https", - "ws", - "wss", - "urn", - "urn:uuid" - ]; - /** @typedef {supportedSchemeNames[number]} SchemeName */ - /** - * @param {string} name - * @returns {name is SchemeName} - */ - function isValidSchemeName(name) { - return supportedSchemeNames.indexOf(name) !== -1; - } - /** - * @callback SchemeFn - * @param {import('../types/index').URIComponent} component - * @param {import('../types/index').Options} options - * @returns {import('../types/index').URIComponent} - */ - /** - * @typedef {Object} SchemeHandler - * @property {SchemeName} scheme - The scheme name. - * @property {boolean} [domainHost] - Indicates if the scheme supports domain hosts. - * @property {SchemeFn} parse - Function to parse the URI component for this scheme. - * @property {SchemeFn} serialize - Function to serialize the URI component for this scheme. - * @property {boolean} [skipNormalize] - Indicates if normalization should be skipped for this scheme. - * @property {boolean} [absolutePath] - Indicates if the scheme uses absolute paths. - * @property {boolean} [unicodeSupport] - Indicates if the scheme supports Unicode. - */ - /** - * @param {import('../types/index').URIComponent} wsComponent - * @returns {boolean} - */ - function wsIsSecure(wsComponent) { - if (wsComponent.secure === true) return true; - else if (wsComponent.secure === false) return false; - else if (wsComponent.scheme) return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S"); - else return false; - } - /** @type {SchemeFn} */ - function httpParse(component) { - if (!component.host) component.error = component.error || "HTTP URIs must have a host."; - return component; - } - /** @type {SchemeFn} */ - function httpSerialize(component) { - const secure = String(component.scheme).toLowerCase() === "https"; - if (component.port === (secure ? 443 : 80) || component.port === "") component.port = void 0; - if (!component.path) component.path = "/"; - return component; - } - /** @type {SchemeFn} */ - function wsParse(wsComponent) { - wsComponent.secure = wsIsSecure(wsComponent); - wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : ""); - wsComponent.path = void 0; - wsComponent.query = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function wsSerialize(wsComponent) { - if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") wsComponent.port = void 0; - if (typeof wsComponent.secure === "boolean") { - wsComponent.scheme = wsComponent.secure ? "wss" : "ws"; - wsComponent.secure = void 0; - } - if (wsComponent.resourceName) { - const [path, query] = wsComponent.resourceName.split("?"); - wsComponent.path = path && path !== "/" ? path : void 0; - wsComponent.query = query; - wsComponent.resourceName = void 0; - } - wsComponent.fragment = void 0; - return wsComponent; - } - /** @type {SchemeFn} */ - function urnParse(urnComponent, options) { - if (!urnComponent.path) { - urnComponent.error = "URN can not be parsed"; - return urnComponent; - } - const matches = urnComponent.path.match(URN_REG); - if (matches) { - const scheme = options.scheme || urnComponent.scheme || "urn"; - urnComponent.nid = matches[1].toLowerCase(); - urnComponent.nss = matches[2]; - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || urnComponent.nid}`); - urnComponent.path = void 0; - if (schemeHandler) urnComponent = schemeHandler.parse(urnComponent, options); - } else urnComponent.error = urnComponent.error || "URN can not be parsed."; - return urnComponent; - } - /** @type {SchemeFn} */ - function urnSerialize(urnComponent, options) { - if (urnComponent.nid === void 0) throw new Error("URN without nid cannot be serialized"); - const scheme = options.scheme || urnComponent.scheme || "urn"; - const nid = urnComponent.nid.toLowerCase(); - const schemeHandler = getSchemeHandler(`${scheme}:${options.nid || nid}`); - if (schemeHandler) urnComponent = schemeHandler.serialize(urnComponent, options); - const uriComponent = urnComponent; - const nss = urnComponent.nss; - uriComponent.path = `${nid || options.nid}:${nss}`; - options.skipEscape = true; - return uriComponent; - } - /** @type {SchemeFn} */ - function urnuuidParse(urnComponent, options) { - const uuidComponent = urnComponent; - uuidComponent.uuid = uuidComponent.nss; - uuidComponent.nss = void 0; - if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) uuidComponent.error = uuidComponent.error || "UUID is not valid."; - return uuidComponent; - } - /** @type {SchemeFn} */ - function urnuuidSerialize(uuidComponent) { - const urnComponent = uuidComponent; - urnComponent.nss = (uuidComponent.uuid || "").toLowerCase(); - return urnComponent; - } - const http = { - scheme: "http", - domainHost: true, - parse: httpParse, - serialize: httpSerialize - }; - const https = { - scheme: "https", - domainHost: http.domainHost, - parse: httpParse, - serialize: httpSerialize - }; - const ws = { - scheme: "ws", - domainHost: true, - parse: wsParse, - serialize: wsSerialize - }; - const wss = { - scheme: "wss", - domainHost: ws.domainHost, - parse: ws.parse, - serialize: ws.serialize - }; - const urn = { - scheme: "urn", - parse: urnParse, - serialize: urnSerialize, - skipNormalize: true - }; - const urnuuid = { - scheme: "urn:uuid", - parse: urnuuidParse, - serialize: urnuuidSerialize, - skipNormalize: true - }; - const SCHEMES = { - http, - https, - ws, - wss, - urn, - "urn:uuid": urnuuid - }; - Object.setPrototypeOf(SCHEMES, null); - /** - * @param {string|undefined} scheme - * @returns {SchemeHandler|undefined} - */ - function getSchemeHandler(scheme) { - return scheme && (SCHEMES[scheme] || SCHEMES[scheme.toLowerCase()]) || void 0; - } - module.exports = { - wsIsSecure, - SCHEMES, - isValidSchemeName, - getSchemeHandler - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/fast-uri@3.1.0/node_modules/fast-uri/index.js -var require_fast_uri = /* @__PURE__ */ __commonJSMin(((exports, module) => { - const { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils(); - const { SCHEMES, getSchemeHandler } = require_schemes(); - /** - * @template {import('./types/index').URIComponent|string} T - * @param {T} uri - * @param {import('./types/index').Options} [options] - * @returns {T} - */ - function normalize(uri, options) { - if (typeof uri === "string") uri = serialize(parse(uri, options), options); - else if (typeof uri === "object") uri = parse(serialize(uri, options), options); - return uri; - } - /** - * @param {string} baseURI - * @param {string} relativeURI - * @param {import('./types/index').Options} [options] - * @returns {string} - */ - function resolve(baseURI, relativeURI, options) { - const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" }; - const resolved = resolveComponent(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true); - schemelessOptions.skipEscape = true; - return serialize(resolved, schemelessOptions); - } - /** - * @param {import ('./types/index').URIComponent} base - * @param {import ('./types/index').URIComponent} relative - * @param {import('./types/index').Options} [options] - * @param {boolean} [skipNormalization=false] - * @returns {import ('./types/index').URIComponent} - */ - function resolveComponent(base, relative, options, skipNormalization) { - /** @type {import('./types/index').URIComponent} */ - const target = {}; - if (!skipNormalization) { - base = parse(serialize(base, options), options); - relative = parse(serialize(relative, options), options); - } - options = options || {}; - if (!options.tolerant && relative.scheme) { - target.scheme = relative.scheme; - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (relative.userinfo !== void 0 || relative.host !== void 0 || relative.port !== void 0) { - target.userinfo = relative.userinfo; - target.host = relative.host; - target.port = relative.port; - target.path = removeDotSegments(relative.path || ""); - target.query = relative.query; - } else { - if (!relative.path) { - target.path = base.path; - if (relative.query !== void 0) target.query = relative.query; - else target.query = base.query; - } else { - if (relative.path[0] === "/") target.path = removeDotSegments(relative.path); - else { - if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) target.path = "/" + relative.path; - else if (!base.path) target.path = relative.path; - else target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path; - target.path = removeDotSegments(target.path); - } - target.query = relative.query; - } - target.userinfo = base.userinfo; - target.host = base.host; - target.port = base.port; - } - target.scheme = base.scheme; - } - target.fragment = relative.fragment; - return target; - } - /** - * @param {import ('./types/index').URIComponent|string} uriA - * @param {import ('./types/index').URIComponent|string} uriB - * @param {import ('./types/index').Options} options - * @returns {boolean} - */ - function equal(uriA, uriB, options) { - if (typeof uriA === "string") { - uriA = unescape(uriA); - uriA = serialize(normalizeComponentEncoding(parse(uriA, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriA === "object") uriA = serialize(normalizeComponentEncoding(uriA, true), { - ...options, - skipEscape: true - }); - if (typeof uriB === "string") { - uriB = unescape(uriB); - uriB = serialize(normalizeComponentEncoding(parse(uriB, options), true), { - ...options, - skipEscape: true - }); - } else if (typeof uriB === "object") uriB = serialize(normalizeComponentEncoding(uriB, true), { - ...options, - skipEscape: true - }); - return uriA.toLowerCase() === uriB.toLowerCase(); - } - /** - * @param {Readonly} cmpts - * @param {import('./types/index').Options} [opts] - * @returns {string} - */ - function serialize(cmpts, opts) { - const component = { - host: cmpts.host, - scheme: cmpts.scheme, - userinfo: cmpts.userinfo, - port: cmpts.port, - path: cmpts.path, - query: cmpts.query, - nid: cmpts.nid, - nss: cmpts.nss, - uuid: cmpts.uuid, - fragment: cmpts.fragment, - reference: cmpts.reference, - resourceName: cmpts.resourceName, - secure: cmpts.secure, - error: "" - }; - const options = Object.assign({}, opts); - const uriTokens = []; - const schemeHandler = getSchemeHandler(options.scheme || component.scheme); - if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options); - if (component.path !== void 0) if (!options.skipEscape) { - component.path = escape(component.path); - if (component.scheme !== void 0) component.path = component.path.split("%3A").join(":"); - } else component.path = unescape(component.path); - if (options.reference !== "suffix" && component.scheme) uriTokens.push(component.scheme, ":"); - const authority = recomposeAuthority(component); - if (authority !== void 0) { - if (options.reference !== "suffix") uriTokens.push("//"); - uriTokens.push(authority); - if (component.path && component.path[0] !== "/") uriTokens.push("/"); - } - if (component.path !== void 0) { - let s = component.path; - if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s); - if (authority === void 0 && s[0] === "/" && s[1] === "/") s = "/%2F" + s.slice(2); - uriTokens.push(s); - } - if (component.query !== void 0) uriTokens.push("?", component.query); - if (component.fragment !== void 0) uriTokens.push("#", component.fragment); - return uriTokens.join(""); - } - const URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u; - /** - * @param {string} uri - * @param {import('./types/index').Options} [opts] - * @returns - */ - function parse(uri, opts) { - const options = Object.assign({}, opts); - /** @type {import('./types/index').URIComponent} */ - const parsed = { - scheme: void 0, - userinfo: void 0, - host: "", - port: void 0, - path: "", - query: void 0, - fragment: void 0 - }; - let isIP = false; - if (options.reference === "suffix") if (options.scheme) uri = options.scheme + ":" + uri; - else uri = "//" + uri; - const matches = uri.match(URI_PARSE); - if (matches) { - parsed.scheme = matches[1]; - parsed.userinfo = matches[3]; - parsed.host = matches[4]; - parsed.port = parseInt(matches[5], 10); - parsed.path = matches[6] || ""; - parsed.query = matches[7]; - parsed.fragment = matches[8]; - if (isNaN(parsed.port)) parsed.port = matches[5]; - if (parsed.host) if (isIPv4(parsed.host) === false) { - const ipv6result = normalizeIPv6(parsed.host); - parsed.host = ipv6result.host.toLowerCase(); - isIP = ipv6result.isIPV6; - } else isIP = true; - if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) parsed.reference = "same-document"; - else if (parsed.scheme === void 0) parsed.reference = "relative"; - else if (parsed.fragment === void 0) parsed.reference = "absolute"; - else parsed.reference = "uri"; - if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) parsed.error = parsed.error || "URI is not a " + options.reference + " reference."; - const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme); - if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) { - if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) try { - parsed.host = URL.domainToASCII(parsed.host.toLowerCase()); - } catch (e) { - parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e; - } - } - if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) { - if (uri.indexOf("%") !== -1) { - if (parsed.scheme !== void 0) parsed.scheme = unescape(parsed.scheme); - if (parsed.host !== void 0) parsed.host = unescape(parsed.host); - } - if (parsed.path) parsed.path = escape(unescape(parsed.path)); - if (parsed.fragment) parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment)); - } - if (schemeHandler && schemeHandler.parse) schemeHandler.parse(parsed, options); - } else parsed.error = parsed.error || "URI can not be parsed."; - return parsed; - } - const fastUri = { - SCHEMES, - normalize, - resolve, - resolveComponent, - equal, - serialize, - parse - }; - module.exports = fastUri; - module.exports.default = fastUri; - module.exports.fastUri = fastUri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/uri.js -var require_uri = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const uri = require_fast_uri(); - uri.code = "require(\"ajv/dist/runtime/uri\").default"; - exports.default = uri; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/core.js -var require_core$3 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - const validation_error_1 = require_validation_error(); - const ref_error_1 = require_ref_error(); - const rules_1 = require_rules(); - const compile_1 = require_compile(); - const codegen_2 = require_codegen(); - const resolve_1 = require_resolve(); - const dataType_1 = require_dataType(); - const util_1 = require_util(); - const $dataRefSchema = require_data(); - const uri_1 = require_uri(); - const defaultRegExp = (str, flags) => new RegExp(str, flags); - defaultRegExp.code = "new RegExp"; - const META_IGNORE_OPTIONS = [ - "removeAdditional", - "useDefaults", - "coerceTypes" - ]; - const EXT_SCOPE_NAMES = new Set([ - "validate", - "serialize", - "parse", - "wrapper", - "root", - "schema", - "keyword", - "pattern", - "formats", - "validate$data", - "func", - "obj", - "Error" - ]); - const removedOptions = { - errorDataPath: "", - format: "`validateFormats: false` can be used instead.", - nullable: "\"nullable\" keyword is supported by default.", - jsonPointers: "Deprecated jsPropertySyntax can be used instead.", - extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.", - missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.", - processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`", - sourceCode: "Use option `code: {source: true}`", - strictDefaults: "It is default now, see option `strict`.", - strictKeywords: "It is default now, see option `strict`.", - uniqueItems: "\"uniqueItems\" keyword is always validated.", - unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).", - cache: "Map is used as cache, schema object as key.", - serialize: "Map is used as cache, schema object as key.", - ajvErrors: "It is default now." - }; - const deprecatedOptions = { - ignoreKeywordsWithRef: "", - jsPropertySyntax: "", - unicode: "\"minLength\"/\"maxLength\" account for unicode characters by default." - }; - const MAX_EXPRESSION = 200; - function requiredOptions(o) { - var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0; - const s = o.strict; - const _optz = (_a = o.code) === null || _a === void 0 ? void 0 : _a.optimize; - const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0; - const regExp = (_c = (_b = o.code) === null || _b === void 0 ? void 0 : _b.regExp) !== null && _c !== void 0 ? _c : defaultRegExp; - const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default; - return { - strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true, - strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true, - strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log", - strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log", - strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false, - code: o.code ? { - ...o.code, - optimize, - regExp - } : { - optimize, - regExp - }, - loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION, - loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION, - meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true, - messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true, - inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true, - schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id", - addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true, - validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true, - validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true, - unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true, - int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true, - uriResolver - }; - } - var Ajv = class { - constructor(opts = {}) { - this.schemas = {}; - this.refs = {}; - this.formats = {}; - this._compilations = /* @__PURE__ */ new Set(); - this._loading = {}; - this._cache = /* @__PURE__ */ new Map(); - opts = this.opts = { - ...opts, - ...requiredOptions(opts) - }; - const { es5, lines } = this.opts.code; - this.scope = new codegen_2.ValueScope({ - scope: {}, - prefixes: EXT_SCOPE_NAMES, - es5, - lines - }); - this.logger = getLogger(opts.logger); - const formatOpt = opts.validateFormats; - opts.validateFormats = false; - this.RULES = (0, rules_1.getRules)(); - checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED"); - checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn"); - this._metaOpts = getMetaSchemaOptions.call(this); - if (opts.formats) addInitialFormats.call(this); - this._addVocabularies(); - this._addDefaultMetaSchema(); - if (opts.keywords) addInitialKeywords.call(this, opts.keywords); - if (typeof opts.meta == "object") this.addMetaSchema(opts.meta); - addInitialSchemas.call(this); - opts.validateFormats = formatOpt; - } - _addVocabularies() { - this.addKeyword("$async"); - } - _addDefaultMetaSchema() { - const { $data, meta, schemaId } = this.opts; - let _dataRefSchema = $dataRefSchema; - if (schemaId === "id") { - _dataRefSchema = { ...$dataRefSchema }; - _dataRefSchema.id = _dataRefSchema.$id; - delete _dataRefSchema.$id; - } - if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false); - } - defaultMeta() { - const { meta, schemaId } = this.opts; - return this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : void 0; - } - validate(schemaKeyRef, data) { - let v; - if (typeof schemaKeyRef == "string") { - v = this.getSchema(schemaKeyRef); - if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`); - } else v = this.compile(schemaKeyRef); - const valid = v(data); - if (!("$async" in v)) this.errors = v.errors; - return valid; - } - compile(schema, _meta) { - const sch = this._addSchema(schema, _meta); - return sch.validate || this._compileSchemaEnv(sch); - } - compileAsync(schema, meta) { - if (typeof this.opts.loadSchema != "function") throw new Error("options.loadSchema should be a function"); - const { loadSchema } = this.opts; - return runCompileAsync.call(this, schema, meta); - async function runCompileAsync(_schema, _meta) { - await loadMetaSchema.call(this, _schema.$schema); - const sch = this._addSchema(_schema, _meta); - return sch.validate || _compileAsync.call(this, sch); - } - async function loadMetaSchema($ref) { - if ($ref && !this.getSchema($ref)) await runCompileAsync.call(this, { $ref }, true); - } - async function _compileAsync(sch) { - try { - return this._compileSchemaEnv(sch); - } catch (e) { - if (!(e instanceof ref_error_1.default)) throw e; - checkLoaded.call(this, e); - await loadMissingSchema.call(this, e.missingSchema); - return _compileAsync.call(this, sch); - } - } - function checkLoaded({ missingSchema: ref, missingRef }) { - if (this.refs[ref]) throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`); - } - async function loadMissingSchema(ref) { - const _schema = await _loadSchema.call(this, ref); - if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema); - if (!this.refs[ref]) this.addSchema(_schema, ref, meta); - } - async function _loadSchema(ref) { - const p = this._loading[ref]; - if (p) return p; - try { - return await (this._loading[ref] = loadSchema(ref)); - } finally { - delete this._loading[ref]; - } - } - } - addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) { - if (Array.isArray(schema)) { - for (const sch of schema) this.addSchema(sch, void 0, _meta, _validateSchema); - return this; - } - let id; - if (typeof schema === "object") { - const { schemaId } = this.opts; - id = schema[schemaId]; - if (id !== void 0 && typeof id != "string") throw new Error(`schema ${schemaId} must be string`); - } - key = (0, resolve_1.normalizeId)(key || id); - this._checkUnique(key); - this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true); - return this; - } - addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) { - this.addSchema(schema, key, true, _validateSchema); - return this; - } - validateSchema(schema, throwOrLogError) { - if (typeof schema == "boolean") return true; - let $schema; - $schema = schema.$schema; - if ($schema !== void 0 && typeof $schema != "string") throw new Error("$schema must be a string"); - $schema = $schema || this.opts.defaultMeta || this.defaultMeta(); - if (!$schema) { - this.logger.warn("meta-schema not available"); - this.errors = null; - return true; - } - const valid = this.validate($schema, schema); - if (!valid && throwOrLogError) { - const message = "schema is invalid: " + this.errorsText(); - if (this.opts.validateSchema === "log") this.logger.error(message); - else throw new Error(message); - } - return valid; - } - getSchema(keyRef) { - let sch; - while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch; - if (sch === void 0) { - const { schemaId } = this.opts; - const root = new compile_1.SchemaEnv({ - schema: {}, - schemaId - }); - sch = compile_1.resolveSchema.call(this, root, keyRef); - if (!sch) return; - this.refs[keyRef] = sch; - } - return sch.validate || this._compileSchemaEnv(sch); - } - removeSchema(schemaKeyRef) { - if (schemaKeyRef instanceof RegExp) { - this._removeAllSchemas(this.schemas, schemaKeyRef); - this._removeAllSchemas(this.refs, schemaKeyRef); - return this; - } - switch (typeof schemaKeyRef) { - case "undefined": - this._removeAllSchemas(this.schemas); - this._removeAllSchemas(this.refs); - this._cache.clear(); - return this; - case "string": { - const sch = getSchEnv.call(this, schemaKeyRef); - if (typeof sch == "object") this._cache.delete(sch.schema); - delete this.schemas[schemaKeyRef]; - delete this.refs[schemaKeyRef]; - return this; - } - case "object": { - const cacheKey = schemaKeyRef; - this._cache.delete(cacheKey); - let id = schemaKeyRef[this.opts.schemaId]; - if (id) { - id = (0, resolve_1.normalizeId)(id); - delete this.schemas[id]; - delete this.refs[id]; - } - return this; - } - default: throw new Error("ajv.removeSchema: invalid parameter"); - } - } - addVocabulary(definitions) { - for (const def of definitions) this.addKeyword(def); - return this; - } - addKeyword(kwdOrDef, def) { - let keyword; - if (typeof kwdOrDef == "string") { - keyword = kwdOrDef; - if (typeof def == "object") { - this.logger.warn("these parameters are deprecated, see docs for addKeyword"); - def.keyword = keyword; - } - } else if (typeof kwdOrDef == "object" && def === void 0) { - def = kwdOrDef; - keyword = def.keyword; - if (Array.isArray(keyword) && !keyword.length) throw new Error("addKeywords: keyword must be string or non-empty array"); - } else throw new Error("invalid addKeywords parameters"); - checkKeyword.call(this, keyword, def); - if (!def) { - (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd)); - return this; - } - keywordMetaschema.call(this, def); - const definition = { - ...def, - type: (0, dataType_1.getJSONTypes)(def.type), - schemaType: (0, dataType_1.getJSONTypes)(def.schemaType) - }; - (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))); - return this; - } - getKeyword(keyword) { - const rule = this.RULES.all[keyword]; - return typeof rule == "object" ? rule.definition : !!rule; - } - removeKeyword(keyword) { - const { RULES } = this; - delete RULES.keywords[keyword]; - delete RULES.all[keyword]; - for (const group of RULES.rules) { - const i = group.rules.findIndex((rule) => rule.keyword === keyword); - if (i >= 0) group.rules.splice(i, 1); - } - return this; - } - addFormat(name, format) { - if (typeof format == "string") format = new RegExp(format); - this.formats[name] = format; - return this; - } - errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) { - if (!errors || errors.length === 0) return "No errors"; - return errors.map((e) => `${dataVar}${e.instancePath} ${e.message}`).reduce((text, msg) => text + separator + msg); - } - $dataMetaSchema(metaSchema, keywordsJsonPointers) { - const rules = this.RULES.all; - metaSchema = JSON.parse(JSON.stringify(metaSchema)); - for (const jsonPointer of keywordsJsonPointers) { - const segments = jsonPointer.split("/").slice(1); - let keywords = metaSchema; - for (const seg of segments) keywords = keywords[seg]; - for (const key in rules) { - const rule = rules[key]; - if (typeof rule != "object") continue; - const { $data } = rule.definition; - const schema = keywords[key]; - if ($data && schema) keywords[key] = schemaOrData(schema); - } - } - return metaSchema; - } - _removeAllSchemas(schemas, regex) { - for (const keyRef in schemas) { - const sch = schemas[keyRef]; - if (!regex || regex.test(keyRef)) { - if (typeof sch == "string") delete schemas[keyRef]; - else if (sch && !sch.meta) { - this._cache.delete(sch.schema); - delete schemas[keyRef]; - } - } - } - } - _addSchema(schema, meta, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) { - let id; - const { schemaId } = this.opts; - if (typeof schema == "object") id = schema[schemaId]; - else if (this.opts.jtd) throw new Error("schema must be object"); - else if (typeof schema != "boolean") throw new Error("schema must be object or boolean"); - let sch = this._cache.get(schema); - if (sch !== void 0) return sch; - baseId = (0, resolve_1.normalizeId)(id || baseId); - const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId); - sch = new compile_1.SchemaEnv({ - schema, - schemaId, - meta, - baseId, - localRefs - }); - this._cache.set(sch.schema, sch); - if (addSchema && !baseId.startsWith("#")) { - if (baseId) this._checkUnique(baseId); - this.refs[baseId] = sch; - } - if (validateSchema) this.validateSchema(schema, true); - return sch; - } - _checkUnique(id) { - if (this.schemas[id] || this.refs[id]) throw new Error(`schema with key or id "${id}" already exists`); - } - _compileSchemaEnv(sch) { - if (sch.meta) this._compileMetaSchema(sch); - else compile_1.compileSchema.call(this, sch); - /* istanbul ignore if */ - if (!sch.validate) throw new Error("ajv implementation error"); - return sch.validate; - } - _compileMetaSchema(sch) { - const currentOpts = this.opts; - this.opts = this._metaOpts; - try { - compile_1.compileSchema.call(this, sch); - } finally { - this.opts = currentOpts; - } - } - }; - Ajv.ValidationError = validation_error_1.default; - Ajv.MissingRefError = ref_error_1.default; - exports.default = Ajv; - function checkOptions(checkOpts, options, msg, log = "error") { - for (const key in checkOpts) { - const opt = key; - if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`); - } - } - function getSchEnv(keyRef) { - keyRef = (0, resolve_1.normalizeId)(keyRef); - return this.schemas[keyRef] || this.refs[keyRef]; - } - function addInitialSchemas() { - const optsSchemas = this.opts.schemas; - if (!optsSchemas) return; - if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas); - else for (const key in optsSchemas) this.addSchema(optsSchemas[key], key); - } - function addInitialFormats() { - for (const name in this.opts.formats) { - const format = this.opts.formats[name]; - if (format) this.addFormat(name, format); - } - } - function addInitialKeywords(defs) { - if (Array.isArray(defs)) { - this.addVocabulary(defs); - return; - } - this.logger.warn("keywords option as map is deprecated, pass array"); - for (const keyword in defs) { - const def = defs[keyword]; - if (!def.keyword) def.keyword = keyword; - this.addKeyword(def); - } - } - function getMetaSchemaOptions() { - const metaOpts = { ...this.opts }; - for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]; - return metaOpts; - } - const noLogs = { - log() {}, - warn() {}, - error() {} - }; - function getLogger(logger) { - if (logger === false) return noLogs; - if (logger === void 0) return console; - if (logger.log && logger.warn && logger.error) return logger; - throw new Error("logger must implement log, warn and error methods"); - } - const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i; - function checkKeyword(keyword, def) { - const { RULES } = this; - (0, util_1.eachItem)(keyword, (kwd) => { - if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`); - if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`); - }); - if (!def) return; - if (def.$data && !("code" in def || "validate" in def)) throw new Error("$data keyword must have \"code\" or \"validate\" function"); - } - function addRule(keyword, definition, dataType) { - var _a; - const post = definition === null || definition === void 0 ? void 0 : definition.post; - if (dataType && post) throw new Error("keyword with \"post\" flag cannot have \"type\""); - const { RULES } = this; - let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t }) => t === dataType); - if (!ruleGroup) { - ruleGroup = { - type: dataType, - rules: [] - }; - RULES.rules.push(ruleGroup); - } - RULES.keywords[keyword] = true; - if (!definition) return; - const rule = { - keyword, - definition: { - ...definition, - type: (0, dataType_1.getJSONTypes)(definition.type), - schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType) - } - }; - if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before); - else ruleGroup.rules.push(rule); - RULES.all[keyword] = rule; - (_a = definition.implements) === null || _a === void 0 || _a.forEach((kwd) => this.addKeyword(kwd)); - } - function addBeforeRule(ruleGroup, rule, before) { - const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before); - if (i >= 0) ruleGroup.rules.splice(i, 0, rule); - else { - ruleGroup.rules.push(rule); - this.logger.warn(`rule ${before} is not defined`); - } - } - function keywordMetaschema(def) { - let { metaSchema } = def; - if (metaSchema === void 0) return; - if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema); - def.validateSchema = this.compile(metaSchema, true); - } - const $dataRef = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" }; - function schemaOrData(schema) { - return { anyOf: [schema, $dataRef] }; - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/id.js -var require_id = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "id", - code() { - throw new Error("NOT SUPPORTED: keyword \"id\", use \"$id\" for schema ID"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/ref.js -var require_ref = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.callRef = exports.getValidate = void 0; - const ref_error_1 = require_ref_error(); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const util_1 = require_util(); - const def = { - keyword: "$ref", - schemaType: "string", - code(cxt) { - const { gen, schema: $ref, it } = cxt; - const { baseId, schemaEnv: env, validateName, opts, self } = it; - const { root } = env; - if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef(); - const schOrEnv = compile_1.resolveRef.call(self, root, baseId, $ref); - if (schOrEnv === void 0) throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref); - if (schOrEnv instanceof compile_1.SchemaEnv) return callValidate(schOrEnv); - return inlineRefSchema(schOrEnv); - function callRootRef() { - if (env === root) return callRef(cxt, validateName, env, env.$async); - const rootName = gen.scopeValue("root", { ref: root }); - return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async); - } - function callValidate(sch) { - callRef(cxt, getValidate(cxt, sch), sch, sch.$async); - } - function inlineRefSchema(sch) { - const schName = gen.scopeValue("schema", opts.code.source === true ? { - ref: sch, - code: (0, codegen_1.stringify)(sch) - } : { ref: sch }); - const valid = gen.name("valid"); - const schCxt = cxt.subschema({ - schema: sch, - dataTypes: [], - schemaPath: codegen_1.nil, - topSchemaRef: schName, - errSchemaPath: $ref - }, valid); - cxt.mergeEvaluated(schCxt); - cxt.ok(valid); - } - } - }; - function getValidate(cxt, sch) { - const { gen } = cxt; - return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`; - } - exports.getValidate = getValidate; - function callRef(cxt, v, sch, $async) { - const { gen, it } = cxt; - const { allErrors, schemaEnv: env, opts } = it; - const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil; - if ($async) callAsyncRef(); - else callSyncRef(); - function callAsyncRef() { - if (!env.$async) throw new Error("async schema referenced by sync schema"); - const valid = gen.let("valid"); - gen.try(() => { - gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v, passCxt)}`); - addEvaluatedFrom(v); - if (!allErrors) gen.assign(valid, true); - }, (e) => { - gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e)); - addErrorsFrom(e); - if (!allErrors) gen.assign(valid, false); - }); - cxt.ok(valid); - } - function callSyncRef() { - cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v)); - } - function addErrorsFrom(source) { - const errs = (0, codegen_1._)`${source}.errors`; - gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`); - gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`); - } - function addEvaluatedFrom(source) { - var _a; - if (!it.opts.unevaluated) return; - const schEvaluated = (_a = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a === void 0 ? void 0 : _a.evaluated; - if (it.props !== true) if (schEvaluated && !schEvaluated.dynamicProps) { - if (schEvaluated.props !== void 0) it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props); - } else { - const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`); - it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name); - } - if (it.items !== true) if (schEvaluated && !schEvaluated.dynamicItems) { - if (schEvaluated.items !== void 0) it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items); - } else { - const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`); - it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name); - } - } - } - exports.callRef = callRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/core/index.js -var require_core$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const id_1 = require_id(); - const ref_1 = require_ref(); - const core = [ - "$schema", - "$id", - "$defs", - "$vocabulary", - { keyword: "$comment" }, - "definitions", - id_1.default, - ref_1.default - ]; - exports.default = core; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitNumber.js -var require_limitNumber = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - maximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - minimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - exclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - exclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const def = { - keyword: Object.keys(KWDs), - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/multipleOf.js -var require_multipleOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "multipleOf", - type: "number", - schemaType: "number", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`, - params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, schemaCode, it } = cxt; - const prec = it.opts.multipleOfPrecision; - const res = gen.let("res"); - const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`; - cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/ucs2length.js -var require_ucs2length = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - function ucs2length(str) { - const len = str.length; - let length = 0; - let pos = 0; - let value; - while (pos < len) { - length++; - value = str.charCodeAt(pos++); - if (value >= 55296 && value <= 56319 && pos < len) { - value = str.charCodeAt(pos); - if ((value & 64512) === 56320) pos++; - } - } - return length; - } - exports.default = ucs2length; - ucs2length.code = "require(\"ajv/dist/runtime/ucs2length\").default"; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitLength.js -var require_limitLength = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const ucs2length_1 = require_ucs2length(); - const def = { - keyword: ["maxLength", "minLength"], - type: "string", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxLength" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode, it } = cxt; - const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT; - const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`; - cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/pattern.js -var require_pattern = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const util_1 = require_util(); - const codegen_1 = require_codegen(); - const def = { - keyword: "pattern", - type: "string", - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const u = it.opts.unicodeRegExp ? "u" : ""; - if ($data) { - const { regExp } = it.opts.code; - const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp); - const valid = gen.let("valid"); - gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false)); - cxt.fail$data((0, codegen_1._)`!${valid}`); - } else { - const regExp = (0, code_1.usePattern)(cxt, schema); - cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitProperties.js -var require_limitProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxProperties", "minProperties"], - type: "object", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxProperties" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/required.js -var require_required = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "required", - type: "object", - schemaType: "array", - $data: true, - error: { - message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`, - params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}` - }, - code(cxt) { - const { gen, schema, schemaCode, data, $data, it } = cxt; - const { opts } = it; - if (!$data && schema.length === 0) return; - const useLoop = schema.length >= opts.loopRequired; - if (it.allErrors) allErrorsMode(); - else exitOnErrorMode(); - if (opts.strictRequired) { - const props = cxt.parentSchema.properties; - const { definedProperties } = cxt.it; - for (const requiredKey of schema) if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) { - const msg = `required property "${requiredKey}" is not defined at "${it.schemaEnv.baseId + it.errSchemaPath}" (strictRequired)`; - (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired); - } - } - function allErrorsMode() { - if (useLoop || $data) cxt.block$data(codegen_1.nil, loopAllRequired); - else for (const prop of schema) (0, code_1.checkReportMissingProp)(cxt, prop); - } - function exitOnErrorMode() { - const missing = gen.let("missing"); - if (useLoop || $data) { - const valid = gen.let("valid", true); - cxt.block$data(valid, () => loopUntilMissing(missing, valid)); - cxt.ok(valid); - } else { - gen.if((0, code_1.checkMissingProp)(cxt, schema, missing)); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - function loopAllRequired() { - gen.forOf("prop", schemaCode, (prop) => { - cxt.setParams({ missingProperty: prop }); - gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error()); - }); - } - function loopUntilMissing(missing, valid) { - cxt.setParams({ missingProperty: missing }); - gen.forOf(missing, schemaCode, () => { - gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties)); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(); - gen.break(); - }); - }, codegen_1.nil); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitItems.js -var require_limitItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: ["maxItems", "minItems"], - type: "array", - schemaType: "number", - $data: true, - error: { - message({ keyword, schemaCode }) { - const comp = keyword === "maxItems" ? "more" : "fewer"; - return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`; - }, - params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}` - }, - code(cxt) { - const { keyword, data, schemaCode } = cxt; - const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT; - cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/runtime/equal.js -var require_equal = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const equal = require_fast_deep_equal(); - equal.code = "require(\"ajv/dist/runtime/equal\").default"; - exports.default = equal; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js -var require_uniqueItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dataType_1 = require_dataType(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "uniqueItems", - type: "array", - schemaType: "boolean", - $data: true, - error: { - message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`, - params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}` - }, - code(cxt) { - const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt; - if (!$data && !schema) return; - const valid = gen.let("valid"); - const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : []; - cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`); - cxt.ok(valid); - function validateUniqueItems() { - const i = gen.let("i", (0, codegen_1._)`${data}.length`); - const j = gen.let("j"); - cxt.setParams({ - i, - j - }); - gen.assign(valid, true); - gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)); - } - function canOptimize() { - return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array"); - } - function loopN(i, j) { - const item = gen.name("item"); - const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong); - const indices = gen.const("indices", (0, codegen_1._)`{}`); - gen.for((0, codegen_1._)`;${i}--;`, () => { - gen.let(item, (0, codegen_1._)`${data}[${i}]`); - gen.if(wrongType, (0, codegen_1._)`continue`); - if (itemTypes.length > 1) gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`); - gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => { - gen.assign(j, (0, codegen_1._)`${indices}[${item}]`); - cxt.error(); - gen.assign(valid, false).break(); - }).code((0, codegen_1._)`${indices}[${item}] = ${i}`); - }); - } - function loopN2(i, j) { - const eql = (0, util_1.useFunc)(gen, equal_1.default); - const outer = gen.name("outer"); - gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => { - cxt.error(); - gen.assign(valid, false).break(outer); - }))); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/const.js -var require_const = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "const", - $data: true, - error: { - message: "must be equal to constant", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schemaCode, schema } = cxt; - if ($data || schema && typeof schema == "object") cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`); - else cxt.fail((0, codegen_1._)`${schema} !== ${data}`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/enum.js -var require_enum = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const equal_1 = require_equal(); - const def = { - keyword: "enum", - schemaType: "array", - $data: true, - error: { - message: "must be equal to one of the allowed values", - params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}` - }, - code(cxt) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - if (!$data && schema.length === 0) throw new Error("enum must have non-empty array"); - const useLoop = schema.length >= it.opts.loopEnum; - let eql; - const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default); - let valid; - if (useLoop || $data) { - valid = gen.let("valid"); - cxt.block$data(valid, loopEnum); - } else { - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const vSchema = gen.const("vSchema", schemaCode); - valid = (0, codegen_1.or)(...schema.map((_x, i) => equalCode(vSchema, i))); - } - cxt.pass(valid); - function loopEnum() { - gen.assign(valid, false); - gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break())); - } - function equalCode(vSchema, i) { - const sch = schema[i]; - return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`; - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/index.js -var require_validation$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const limitNumber_1 = require_limitNumber(); - const multipleOf_1 = require_multipleOf(); - const limitLength_1 = require_limitLength(); - const pattern_1 = require_pattern(); - const limitProperties_1 = require_limitProperties(); - const required_1 = require_required(); - const limitItems_1 = require_limitItems(); - const uniqueItems_1 = require_uniqueItems(); - const const_1 = require_const(); - const enum_1 = require_enum(); - const validation = [ - limitNumber_1.default, - multipleOf_1.default, - limitLength_1.default, - pattern_1.default, - limitProperties_1.default, - required_1.default, - limitItems_1.default, - uniqueItems_1.default, - { - keyword: "type", - schemaType: ["string", "array"] - }, - { - keyword: "nullable", - schemaType: "boolean" - }, - const_1.default, - enum_1.default - ]; - exports.default = validation; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js -var require_additionalItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateAdditionalItems = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "additionalItems", - type: "array", - schemaType: ["boolean", "object"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { parentSchema, it } = cxt; - const { items } = parentSchema; - if (!Array.isArray(items)) { - (0, util_1.checkStrictMode)(it, "\"additionalItems\" is ignored when \"items\" is not an array of schemas"); - return; - } - validateAdditionalItems(cxt, items); - } - }; - function validateAdditionalItems(cxt, items) { - const { gen, schema, data, keyword, it } = cxt; - it.items = true; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items.length }); - cxt.pass((0, codegen_1._)`${len} <= ${items.length}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid)); - cxt.ok(valid); - } - function validateItems(valid) { - gen.forRange("i", items.length, len, (i) => { - cxt.subschema({ - keyword, - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - exports.validateAdditionalItems = validateAdditionalItems; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items.js -var require_items = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateTuple = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const def = { - keyword: "items", - type: "array", - schemaType: [ - "object", - "array", - "boolean" - ], - before: "uniqueItems", - code(cxt) { - const { schema, it } = cxt; - if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema); - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - function validateTuple(cxt, extraItems, schArr = cxt.schema) { - const { gen, parentSchema, data, keyword, it } = cxt; - checkStrictTuple(parentSchema); - if (it.opts.unevaluated && schArr.length && it.items !== true) it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items); - const valid = gen.name("valid"); - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - schArr.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({ - keyword, - schemaProp: i, - dataProp: i - }, valid)); - cxt.ok(valid); - }); - function checkStrictTuple(sch) { - const { opts, errSchemaPath } = it; - const l = schArr.length; - const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false); - if (opts.strictTuples && !fullTuple) { - const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`; - (0, util_1.checkStrictMode)(it, msg, opts.strictTuples); - } - } - } - exports.validateTuple = validateTuple; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js -var require_prefixItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const items_1 = require_items(); - const def = { - keyword: "prefixItems", - type: "array", - schemaType: ["array"], - before: "uniqueItems", - code: (cxt) => (0, items_1.validateTuple)(cxt, "items") - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/items2020.js -var require_items2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - const additionalItems_1 = require_additionalItems(); - const def = { - keyword: "items", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { schema, parentSchema, it } = cxt; - const { prefixItems } = parentSchema; - it.items = true; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - if (prefixItems) (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems); - else cxt.ok((0, code_1.validateArray)(cxt)); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/contains.js -var require_contains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "contains", - type: "array", - schemaType: ["object", "boolean"], - before: "uniqueItems", - trackErrors: true, - error: { - message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`, - params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - let min; - let max; - const { minContains, maxContains } = parentSchema; - if (it.opts.next) { - min = minContains === void 0 ? 1 : minContains; - max = maxContains; - } else min = 1; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - cxt.setParams({ - min, - max - }); - if (max === void 0 && min === 0) { - (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`); - return; - } - if (max !== void 0 && min > max) { - (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`); - cxt.fail(); - return; - } - if ((0, util_1.alwaysValidSchema)(it, schema)) { - let cond = (0, codegen_1._)`${len} >= ${min}`; - if (max !== void 0) cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`; - cxt.pass(cond); - return; - } - it.items = true; - const valid = gen.name("valid"); - if (max === void 0 && min === 1) validateItems(valid, () => gen.if(valid, () => gen.break())); - else if (min === 0) { - gen.let(valid, true); - if (max !== void 0) gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount); - } else { - gen.let(valid, false); - validateItemsWithCount(); - } - cxt.result(valid, () => cxt.reset()); - function validateItemsWithCount() { - const schValid = gen.name("_valid"); - const count = gen.let("count", 0); - validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))); - } - function validateItems(_valid, block) { - gen.forRange("i", 0, len, (i) => { - cxt.subschema({ - keyword: "contains", - dataProp: i, - dataPropType: util_1.Type.Num, - compositeRule: true - }, _valid); - block(); - }); - } - function checkLimits(count) { - gen.code((0, codegen_1._)`${count}++`); - if (max === void 0) gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break()); - else { - gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break()); - if (min === 1) gen.assign(valid, true); - else gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true)); - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependencies.js -var require_dependencies = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0; - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const code_1 = require_code(); - exports.error = { - message: ({ params: { property, depsCount, deps } }) => { - const property_ies = depsCount === 1 ? "property" : "properties"; - return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`; - }, - params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property}, - missingProperty: ${missingProperty}, - depsCount: ${depsCount}, - deps: ${deps}}` - }; - const def = { - keyword: "dependencies", - type: "object", - schemaType: "object", - error: exports.error, - code(cxt) { - const [propDeps, schDeps] = splitDependencies(cxt); - validatePropertyDeps(cxt, propDeps); - validateSchemaDeps(cxt, schDeps); - } - }; - function splitDependencies({ schema }) { - const propertyDeps = {}; - const schemaDeps = {}; - for (const key in schema) { - if (key === "__proto__") continue; - const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps; - deps[key] = schema[key]; - } - return [propertyDeps, schemaDeps]; - } - function validatePropertyDeps(cxt, propertyDeps = cxt.schema) { - const { gen, data, it } = cxt; - if (Object.keys(propertyDeps).length === 0) return; - const missing = gen.let("missing"); - for (const prop in propertyDeps) { - const deps = propertyDeps[prop]; - if (deps.length === 0) continue; - const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties); - cxt.setParams({ - property: prop, - depsCount: deps.length, - deps: deps.join(", ") - }); - if (it.allErrors) gen.if(hasProperty, () => { - for (const depProp of deps) (0, code_1.checkReportMissingProp)(cxt, depProp); - }); - else { - gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`); - (0, code_1.reportMissingProp)(cxt, missing); - gen.else(); - } - } - } - exports.validatePropertyDeps = validatePropertyDeps; - function validateSchemaDeps(cxt, schemaDeps = cxt.schema) { - const { gen, data, keyword, it } = cxt; - const valid = gen.name("valid"); - for (const prop in schemaDeps) { - if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop])) continue; - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties), () => { - const schCxt = cxt.subschema({ - keyword, - schemaProp: prop - }, valid); - cxt.mergeValidEvaluated(schCxt, valid); - }, () => gen.var(valid, true)); - cxt.ok(valid); - } - } - exports.validateSchemaDeps = validateSchemaDeps; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js -var require_propertyNames = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "propertyNames", - type: "object", - schemaType: ["object", "boolean"], - error: { - message: "property name must be valid", - params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) return; - const valid = gen.name("valid"); - gen.forIn("key", data, (key) => { - cxt.setParams({ propertyName: key }); - cxt.subschema({ - keyword: "propertyNames", - data: key, - dataTypes: ["string"], - propertyName: key, - compositeRule: true - }, valid); - gen.if((0, codegen_1.not)(valid), () => { - cxt.error(true); - if (!it.allErrors) gen.break(); - }); - }); - cxt.ok(valid); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js -var require_additionalProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const util_1 = require_util(); - const def = { - keyword: "additionalProperties", - type: ["object"], - schemaType: ["boolean", "object"], - allowUndefined: true, - trackErrors: true, - error: { - message: "must NOT have additional properties", - params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}` - }, - code(cxt) { - const { gen, schema, parentSchema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, opts } = it; - it.props = true; - if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema)) return; - const props = (0, code_1.allSchemaProperties)(parentSchema.properties); - const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties); - checkAdditionalProperties(); - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function checkAdditionalProperties() { - gen.forIn("key", data, (key) => { - if (!props.length && !patProps.length) additionalPropertyCode(key); - else gen.if(isAdditional(key), () => additionalPropertyCode(key)); - }); - } - function isAdditional(key) { - let definedProp; - if (props.length > 8) { - const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties"); - definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key); - } else if (props.length) definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`)); - else definedProp = codegen_1.nil; - if (patProps.length) definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`)); - return (0, codegen_1.not)(definedProp); - } - function deleteAdditional(key) { - gen.code((0, codegen_1._)`delete ${data}[${key}]`); - } - function additionalPropertyCode(key) { - if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) { - deleteAdditional(key); - return; - } - if (schema === false) { - cxt.setParams({ additionalProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - if (opts.removeAdditional === "failing") { - applyAdditionalSchema(key, valid, false); - gen.if((0, codegen_1.not)(valid), () => { - cxt.reset(); - deleteAdditional(key); - }); - } else { - applyAdditionalSchema(key, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - } - function applyAdditionalSchema(key, valid, errors) { - const subschema = { - keyword: "additionalProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }; - if (errors === false) Object.assign(subschema, { - compositeRule: true, - createErrors: false, - allErrors: false - }); - cxt.subschema(subschema, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/properties.js -var require_properties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const validate_1 = require_validate(); - const code_1 = require_code(); - const util_1 = require_util(); - const additionalProperties_1 = require_additionalProperties(); - const def = { - keyword: "properties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, parentSchema, data, it } = cxt; - if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties")); - const allProps = (0, code_1.allSchemaProperties)(schema); - for (const prop of allProps) it.definedProperties.add(prop); - if (it.opts.unevaluated && allProps.length && it.props !== true) it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props); - const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p])); - if (properties.length === 0) return; - const valid = gen.name("valid"); - for (const prop of properties) { - if (hasDefault(prop)) applyPropertySchema(prop); - else { - gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties)); - applyPropertySchema(prop); - if (!it.allErrors) gen.else().var(valid, true); - gen.endIf(); - } - cxt.it.definedProperties.add(prop); - cxt.ok(valid); - } - function hasDefault(prop) { - return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0; - } - function applyPropertySchema(prop) { - cxt.subschema({ - keyword: "properties", - schemaProp: prop, - dataProp: prop - }, valid); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js -var require_patternProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const code_1 = require_code(); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const util_2 = require_util(); - const def = { - keyword: "patternProperties", - type: "object", - schemaType: "object", - code(cxt) { - const { gen, schema, data, parentSchema, it } = cxt; - const { opts } = it; - const patterns = (0, code_1.allSchemaProperties)(schema); - const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p])); - if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) return; - const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties; - const valid = gen.name("valid"); - if (it.props !== true && !(it.props instanceof codegen_1.Name)) it.props = (0, util_2.evaluatedPropsToName)(gen, it.props); - const { props } = it; - validatePatternProperties(); - function validatePatternProperties() { - for (const pat of patterns) { - if (checkProperties) checkMatchingProperties(pat); - if (it.allErrors) validateProperties(pat); - else { - gen.var(valid, true); - validateProperties(pat); - gen.if(valid); - } - } - } - function checkMatchingProperties(pat) { - for (const prop in checkProperties) if (new RegExp(pat).test(prop)) (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`); - } - function validateProperties(pat) { - gen.forIn("key", data, (key) => { - gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => { - const alwaysValid = alwaysValidPatterns.includes(pat); - if (!alwaysValid) cxt.subschema({ - keyword: "patternProperties", - schemaProp: pat, - dataProp: key, - dataPropType: util_2.Type.Str - }, valid); - if (it.opts.unevaluated && props !== true) gen.assign((0, codegen_1._)`${props}[${key}]`, true); - else if (!alwaysValid && !it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/not.js -var require_not = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "not", - schemaType: ["object", "boolean"], - trackErrors: true, - code(cxt) { - const { gen, schema, it } = cxt; - if ((0, util_1.alwaysValidSchema)(it, schema)) { - cxt.fail(); - return; - } - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "not", - compositeRule: true, - createErrors: false, - allErrors: false - }, valid); - cxt.failResult(valid, () => cxt.reset(), () => cxt.error()); - }, - error: { message: "must NOT be valid" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/anyOf.js -var require_anyOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const def = { - keyword: "anyOf", - schemaType: "array", - trackErrors: true, - code: require_code().validateUnion, - error: { message: "must match a schema in anyOf" } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/oneOf.js -var require_oneOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "oneOf", - schemaType: "array", - trackErrors: true, - error: { - message: "must match exactly one schema in oneOf", - params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}` - }, - code(cxt) { - const { gen, schema, parentSchema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - if (it.opts.discriminator && parentSchema.discriminator) return; - const schArr = schema; - const valid = gen.let("valid", false); - const passing = gen.let("passing", null); - const schValid = gen.name("_valid"); - cxt.setParams({ passing }); - gen.block(validateOneOf); - cxt.result(valid, () => cxt.reset(), () => cxt.error(true)); - function validateOneOf() { - schArr.forEach((sch, i) => { - let schCxt; - if ((0, util_1.alwaysValidSchema)(it, sch)) gen.var(schValid, true); - else schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp: i, - compositeRule: true - }, schValid); - if (i > 0) gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else(); - gen.if(schValid, () => { - gen.assign(valid, true); - gen.assign(passing, i); - if (schCxt) cxt.mergeEvaluated(schCxt, codegen_1.Name); - }); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/allOf.js -var require_allOf = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: "allOf", - schemaType: "array", - code(cxt) { - const { gen, schema, it } = cxt; - /* istanbul ignore if */ - if (!Array.isArray(schema)) throw new Error("ajv implementation error"); - const valid = gen.name("valid"); - schema.forEach((sch, i) => { - if ((0, util_1.alwaysValidSchema)(it, sch)) return; - const schCxt = cxt.subschema({ - keyword: "allOf", - schemaProp: i - }, valid); - cxt.ok(valid); - cxt.mergeEvaluated(schCxt); - }); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/if.js -var require_if = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "if", - schemaType: ["object", "boolean"], - trackErrors: true, - error: { - message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`, - params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}` - }, - code(cxt) { - const { gen, parentSchema, it } = cxt; - if (parentSchema.then === void 0 && parentSchema.else === void 0) (0, util_1.checkStrictMode)(it, "\"if\" without \"then\" and \"else\" is ignored"); - const hasThen = hasSchema(it, "then"); - const hasElse = hasSchema(it, "else"); - if (!hasThen && !hasElse) return; - const valid = gen.let("valid", true); - const schValid = gen.name("_valid"); - validateIf(); - cxt.reset(); - if (hasThen && hasElse) { - const ifClause = gen.let("ifClause"); - cxt.setParams({ ifClause }); - gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)); - } else if (hasThen) gen.if(schValid, validateClause("then")); - else gen.if((0, codegen_1.not)(schValid), validateClause("else")); - cxt.pass(valid, () => cxt.error(true)); - function validateIf() { - const schCxt = cxt.subschema({ - keyword: "if", - compositeRule: true, - createErrors: false, - allErrors: false - }, schValid); - cxt.mergeEvaluated(schCxt); - } - function validateClause(keyword, ifClause) { - return () => { - const schCxt = cxt.subschema({ keyword }, schValid); - gen.assign(valid, schValid); - cxt.mergeValidEvaluated(schCxt, valid); - if (ifClause) gen.assign(ifClause, (0, codegen_1._)`${keyword}`); - else cxt.setParams({ ifClause: keyword }); - }; - } - } - }; - function hasSchema(it, keyword) { - const schema = it.schema[keyword]; - return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/thenElse.js -var require_thenElse = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["then", "else"], - schemaType: ["object", "boolean"], - code({ keyword, parentSchema, it }) { - if (parentSchema.if === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/index.js -var require_applicator$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const additionalItems_1 = require_additionalItems(); - const prefixItems_1 = require_prefixItems(); - const items_1 = require_items(); - const items2020_1 = require_items2020(); - const contains_1 = require_contains(); - const dependencies_1 = require_dependencies(); - const propertyNames_1 = require_propertyNames(); - const additionalProperties_1 = require_additionalProperties(); - const properties_1 = require_properties(); - const patternProperties_1 = require_patternProperties(); - const not_1 = require_not(); - const anyOf_1 = require_anyOf(); - const oneOf_1 = require_oneOf(); - const allOf_1 = require_allOf(); - const if_1 = require_if(); - const thenElse_1 = require_thenElse(); - function getApplicator(draft2020 = false) { - const applicator = [ - not_1.default, - anyOf_1.default, - oneOf_1.default, - allOf_1.default, - if_1.default, - thenElse_1.default, - propertyNames_1.default, - additionalProperties_1.default, - dependencies_1.default, - properties_1.default, - patternProperties_1.default - ]; - if (draft2020) applicator.push(prefixItems_1.default, items2020_1.default); - else applicator.push(additionalItems_1.default, items_1.default); - applicator.push(contains_1.default); - return applicator; - } - exports.default = getApplicator; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/format.js -var require_format$2 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const def = { - keyword: "format", - type: ["number", "string"], - schemaType: "string", - $data: true, - error: { - message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`, - params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}` - }, - code(cxt, ruleType) { - const { gen, data, $data, schema, schemaCode, it } = cxt; - const { opts, errSchemaPath, schemaEnv, self } = it; - if (!opts.validateFormats) return; - if ($data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`); - const fType = gen.let("fType"); - const format = gen.let("format"); - gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef)); - cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt())); - function unknownFmt() { - if (opts.strictSchema === false) return codegen_1.nil; - return (0, codegen_1._)`${schemaCode} && !${format}`; - } - function invalidFmt() { - const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`; - const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`; - return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`; - } - } - function validateFormat() { - const formatDef = self.formats[schema]; - if (!formatDef) { - unknownFormat(); - return; - } - if (formatDef === true) return; - const [fmtType, format, fmtRef] = getFormat(formatDef); - if (fmtType === ruleType) cxt.pass(validCondition()); - function unknownFormat() { - if (opts.strictSchema === false) { - self.logger.warn(unknownMsg()); - return; - } - throw new Error(unknownMsg()); - function unknownMsg() { - return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`; - } - } - function getFormat(fmtDef) { - const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0; - const fmt = gen.scopeValue("formats", { - key: schema, - ref: fmtDef, - code - }); - if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) return [ - fmtDef.type || "string", - fmtDef.validate, - (0, codegen_1._)`${fmt}.validate` - ]; - return [ - "string", - fmtDef, - fmt - ]; - } - function validCondition() { - if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) { - if (!schemaEnv.$async) throw new Error("async format in sync schema"); - return (0, codegen_1._)`await ${fmtRef}(${data})`; - } - return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/format/index.js -var require_format$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const format = [require_format$2().default]; - exports.default = format; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/metadata.js -var require_metadata = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.contentVocabulary = exports.metadataVocabulary = void 0; - exports.metadataVocabulary = [ - "title", - "description", - "default", - "deprecated", - "readOnly", - "writeOnly", - "examples" - ]; - exports.contentVocabulary = [ - "contentMediaType", - "contentEncoding", - "contentSchema" - ]; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft7.js -var require_draft7 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft7Vocabularies = [ - core_1.default, - validation_1.default, - (0, applicator_1.default)(), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary - ]; - exports.default = draft7Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/types.js -var require_types = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.DiscrError = void 0; - var DiscrError; - (function(DiscrError) { - DiscrError["Tag"] = "tag"; - DiscrError["Mapping"] = "mapping"; - })(DiscrError || (exports.DiscrError = DiscrError = {})); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/discriminator/index.js -var require_discriminator = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const types_1 = require_types(); - const compile_1 = require_compile(); - const ref_error_1 = require_ref_error(); - const util_1 = require_util(); - const def = { - keyword: "discriminator", - type: "object", - schemaType: "object", - error: { - message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`, - params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}` - }, - code(cxt) { - const { gen, data, schema, parentSchema, it } = cxt; - const { oneOf } = parentSchema; - if (!it.opts.discriminator) throw new Error("discriminator: requires discriminator option"); - const tagName = schema.propertyName; - if (typeof tagName != "string") throw new Error("discriminator: requires propertyName"); - if (schema.mapping) throw new Error("discriminator: mapping is not supported"); - if (!oneOf) throw new Error("discriminator: requires oneOf keyword"); - const valid = gen.let("valid", false); - const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`); - gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { - discrError: types_1.DiscrError.Tag, - tag, - tagName - })); - cxt.ok(valid); - function validateMapping() { - const mapping = getMapping(); - gen.if(false); - for (const tagValue in mapping) { - gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`); - gen.assign(valid, applyTagSchema(mapping[tagValue])); - } - gen.else(); - cxt.error(false, { - discrError: types_1.DiscrError.Mapping, - tag, - tagName - }); - gen.endIf(); - } - function applyTagSchema(schemaProp) { - const _valid = gen.name("valid"); - const schCxt = cxt.subschema({ - keyword: "oneOf", - schemaProp - }, _valid); - cxt.mergeEvaluated(schCxt, codegen_1.Name); - return _valid; - } - function getMapping() { - var _a; - const oneOfMapping = {}; - const topRequired = hasRequired(parentSchema); - let tagRequired = true; - for (let i = 0; i < oneOf.length; i++) { - let sch = oneOf[i]; - if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) { - const ref = sch.$ref; - sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref); - if (sch instanceof compile_1.SchemaEnv) sch = sch.schema; - if (sch === void 0) throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref); - } - const propSch = (_a = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a === void 0 ? void 0 : _a[tagName]; - if (typeof propSch != "object") throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`); - tagRequired = tagRequired && (topRequired || hasRequired(sch)); - addMappings(propSch, i); - } - if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`); - return oneOfMapping; - function hasRequired({ required }) { - return Array.isArray(required) && required.includes(tagName); - } - function addMappings(sch, i) { - if (sch.const) addMapping(sch.const, i); - else if (sch.enum) for (const tagValue of sch.enum) addMapping(tagValue, i); - else throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`); - } - function addMapping(tagValue, i) { - if (typeof tagValue != "string" || tagValue in oneOfMapping) throw new Error(`discriminator: "${tagName}" values must be unique strings`); - oneOfMapping[tagValue] = i; - } - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-draft-07.json -var require_json_schema_draft_07 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "http://json-schema.org/draft-07/schema#", - "title": "Core schema meta-schema", - "definitions": { - "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$ref": "#" } - }, - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { "allOf": [{ "$ref": "#/definitions/nonNegativeInteger" }, { "default": 0 }] }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - }, - "type": ["object", "boolean"], - "properties": { - "$id": { - "type": "string", - "format": "uri-reference" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "$ref": { - "type": "string", - "format": "uri-reference" - }, - "$comment": { "type": "string" }, - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "readOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - }, - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/definitions/nonNegativeInteger" }, - "minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "additionalItems": { "$ref": "#" }, - "items": { - "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/schemaArray" }], - "default": true - }, - "maxItems": { "$ref": "#/definitions/nonNegativeInteger" }, - "minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "contains": { "$ref": "#" }, - "maxProperties": { "$ref": "#/definitions/nonNegativeInteger" }, - "minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/definitions/stringArray" }, - "additionalProperties": { "$ref": "#" }, - "definitions": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "properties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$ref": "#" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependencies": { - "type": "object", - "additionalProperties": { "anyOf": [{ "$ref": "#" }, { "$ref": "#/definitions/stringArray" }] } - }, - "propertyNames": { "$ref": "#" }, - "const": true, - "enum": { - "type": "array", - "items": true, - "minItems": 1, - "uniqueItems": true - }, - "type": { "anyOf": [{ "$ref": "#/definitions/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/definitions/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "format": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "if": { "$ref": "#" }, - "then": { "$ref": "#" }, - "else": { "$ref": "#" }, - "allOf": { "$ref": "#/definitions/schemaArray" }, - "anyOf": { "$ref": "#/definitions/schemaArray" }, - "oneOf": { "$ref": "#/definitions/schemaArray" }, - "not": { "$ref": "#" } - }, - "default": true - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/ajv.js -var require_ajv = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const discriminator_1 = require_discriminator(); - const draft7MetaSchema = require_json_schema_draft_07(); - const META_SUPPORT_DATA = ["/properties"]; - const META_SCHEMA_ID = "http://json-schema.org/draft-07/schema"; - var Ajv = class extends core_1.default { - _addVocabularies() { - super._addVocabularies(); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - if (!this.opts.meta) return; - const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema; - this.addMetaSchema(metaSchema, META_SCHEMA_ID, false); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv = Ajv; - module.exports = exports = Ajv; - module.exports.Ajv = Ajv; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicAnchor.js -var require_dynamicAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicAnchor = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const compile_1 = require_compile(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicAnchor", - schemaType: "string", - code: (cxt) => dynamicAnchor(cxt, cxt.schema) - }; - function dynamicAnchor(cxt, anchor) { - const { gen, it } = cxt; - it.schemaEnv.root.dynamicAnchors[anchor] = true; - const v = (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`; - const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt); - gen.if((0, codegen_1._)`!${v}`, () => gen.assign(v, validate)); - } - exports.dynamicAnchor = dynamicAnchor; - function _getValidate(cxt) { - const { schemaEnv, schema, self } = cxt.it; - const { root, baseId, localRefs, meta } = schemaEnv.root; - const { schemaId } = self.opts; - const sch = new compile_1.SchemaEnv({ - schema, - schemaId, - root, - baseId, - localRefs, - meta - }); - compile_1.compileSchema.call(self, sch); - return (0, ref_1.getValidate)(cxt, sch); - } - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/dynamicRef.js -var require_dynamicRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.dynamicRef = void 0; - const codegen_1 = require_codegen(); - const names_1 = require_names(); - const ref_1 = require_ref(); - const def = { - keyword: "$dynamicRef", - schemaType: "string", - code: (cxt) => dynamicRef(cxt, cxt.schema) - }; - function dynamicRef(cxt, ref) { - const { gen, keyword, it } = cxt; - if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`); - const anchor = ref.slice(1); - if (it.allErrors) _dynamicRef(); - else { - const valid = gen.let("valid", false); - _dynamicRef(valid); - cxt.ok(valid); - } - function _dynamicRef(valid) { - if (it.schemaEnv.root.dynamicAnchors[anchor]) { - const v = gen.let("_v", (0, codegen_1._)`${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`); - gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)); - } else _callRef(it.validateName, valid)(); - } - function _callRef(validate, valid) { - return valid ? () => gen.block(() => { - (0, ref_1.callRef)(cxt, validate); - gen.let(valid, true); - }) : () => (0, ref_1.callRef)(cxt, validate); - } - } - exports.dynamicRef = dynamicRef; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveAnchor.js -var require_recursiveAnchor = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const util_1 = require_util(); - const def = { - keyword: "$recursiveAnchor", - schemaType: "boolean", - code(cxt) { - if (cxt.schema) (0, dynamicAnchor_1.dynamicAnchor)(cxt, ""); - else (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored"); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/recursiveRef.js -var require_recursiveRef = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicRef_1 = require_dynamicRef(); - const def = { - keyword: "$recursiveRef", - schemaType: "string", - code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/dynamic/index.js -var require_dynamic = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dynamicAnchor_1 = require_dynamicAnchor(); - const dynamicRef_1 = require_dynamicRef(); - const recursiveAnchor_1 = require_recursiveAnchor(); - const recursiveRef_1 = require_recursiveRef(); - const dynamic = [ - dynamicAnchor_1.default, - dynamicRef_1.default, - recursiveAnchor_1.default, - recursiveRef_1.default - ]; - exports.default = dynamic; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/dependentRequired.js -var require_dependentRequired = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentRequired", - type: "object", - schemaType: "object", - error: dependencies_1.error, - code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/applicator/dependentSchemas.js -var require_dependentSchemas = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependencies_1 = require_dependencies(); - const def = { - keyword: "dependentSchemas", - type: "object", - schemaType: "object", - code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt) - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/validation/limitContains.js -var require_limitContains = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const util_1 = require_util(); - const def = { - keyword: ["maxContains", "minContains"], - type: "array", - schemaType: "number", - code({ keyword, parentSchema, it }) { - if (parentSchema.contains === void 0) (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`); - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/next.js -var require_next = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const dependentRequired_1 = require_dependentRequired(); - const dependentSchemas_1 = require_dependentSchemas(); - const limitContains_1 = require_limitContains(); - const next = [ - dependentRequired_1.default, - dependentSchemas_1.default, - limitContains_1.default - ]; - exports.default = next; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedProperties.js -var require_unevaluatedProperties = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const names_1 = require_names(); - const def = { - keyword: "unevaluatedProperties", - type: "object", - schemaType: ["boolean", "object"], - trackErrors: true, - error: { - message: "must NOT have unevaluated properties", - params: ({ params }) => (0, codegen_1._)`{unevaluatedProperty: ${params.unevaluatedProperty}}` - }, - code(cxt) { - const { gen, schema, data, errsCount, it } = cxt; - /* istanbul ignore if */ - if (!errsCount) throw new Error("ajv implementation error"); - const { allErrors, props } = it; - if (props instanceof codegen_1.Name) gen.if((0, codegen_1._)`${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key)))); - else if (props !== true) gen.forIn("key", data, (key) => props === void 0 ? unevaluatedPropCode(key) : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key))); - it.props = true; - cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`); - function unevaluatedPropCode(key) { - if (schema === false) { - cxt.setParams({ unevaluatedProperty: key }); - cxt.error(); - if (!allErrors) gen.break(); - return; - } - if (!(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.name("valid"); - cxt.subschema({ - keyword: "unevaluatedProperties", - dataProp: key, - dataPropType: util_1.Type.Str - }, valid); - if (!allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - } - } - function unevaluatedDynamic(evaluatedProps, key) { - return (0, codegen_1._)`!${evaluatedProps} || !${evaluatedProps}[${key}]`; - } - function unevaluatedStatic(evaluatedProps, key) { - const ps = []; - for (const p in evaluatedProps) if (evaluatedProps[p] === true) ps.push((0, codegen_1._)`${key} !== ${p}`); - return (0, codegen_1.and)(...ps); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/unevaluatedItems.js -var require_unevaluatedItems = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const codegen_1 = require_codegen(); - const util_1 = require_util(); - const def = { - keyword: "unevaluatedItems", - type: "array", - schemaType: ["boolean", "object"], - error: { - message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`, - params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}` - }, - code(cxt) { - const { gen, schema, data, it } = cxt; - const items = it.items || 0; - if (items === true) return; - const len = gen.const("len", (0, codegen_1._)`${data}.length`); - if (schema === false) { - cxt.setParams({ len: items }); - cxt.fail((0, codegen_1._)`${len} > ${items}`); - } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) { - const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items}`); - gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items)); - cxt.ok(valid); - } - it.items = true; - function validateItems(valid, from) { - gen.forRange("i", from, len, (i) => { - cxt.subschema({ - keyword: "unevaluatedItems", - dataProp: i, - dataPropType: util_1.Type.Num - }, valid); - if (!it.allErrors) gen.if((0, codegen_1.not)(valid), () => gen.break()); - }); - } - } - }; - exports.default = def; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/unevaluated/index.js -var require_unevaluated$1 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const unevaluatedProperties_1 = require_unevaluatedProperties(); - const unevaluatedItems_1 = require_unevaluatedItems(); - const unevaluated = [unevaluatedProperties_1.default, unevaluatedItems_1.default]; - exports.default = unevaluated; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/schema.json -var require_schema$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/schema", - "$vocabulary": { - "https://json-schema.org/draft/2019-09/vocab/core": true, - "https://json-schema.org/draft/2019-09/vocab/applicator": true, - "https://json-schema.org/draft/2019-09/vocab/validation": true, - "https://json-schema.org/draft/2019-09/vocab/meta-data": true, - "https://json-schema.org/draft/2019-09/vocab/format": false, - "https://json-schema.org/draft/2019-09/vocab/content": true - }, - "$recursiveAnchor": true, - "title": "Core and Validation specifications meta-schema", - "allOf": [ - { "$ref": "meta/core" }, - { "$ref": "meta/applicator" }, - { "$ref": "meta/validation" }, - { "$ref": "meta/meta-data" }, - { "$ref": "meta/format" }, - { "$ref": "meta/content" } - ], - "type": ["object", "boolean"], - "properties": { - "definitions": { - "$comment": "While no longer an official keyword as it is replaced by $defs, this keyword is retained in the meta-schema to prevent incompatible extensions as it remains in common use.", - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - }, - "dependencies": { - "$comment": "\"dependencies\" is no longer a keyword, but schema authors should avoid redefining it to facilitate a smooth transition to \"dependentSchemas\" and \"dependentRequired\"", - "type": "object", - "additionalProperties": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "meta/validation#/$defs/stringArray" }] } - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/applicator.json -var require_applicator$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/applicator", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/applicator": true }, - "$recursiveAnchor": true, - "title": "Applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "additionalItems": { "$recursiveRef": "#" }, - "unevaluatedItems": { "$recursiveRef": "#" }, - "items": { "anyOf": [{ "$recursiveRef": "#" }, { "$ref": "#/$defs/schemaArray" }] }, - "contains": { "$recursiveRef": "#" }, - "additionalProperties": { "$recursiveRef": "#" }, - "unevaluatedProperties": { "$recursiveRef": "#" }, - "properties": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependentSchemas": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" } - }, - "propertyNames": { "$recursiveRef": "#" }, - "if": { "$recursiveRef": "#" }, - "then": { "$recursiveRef": "#" }, - "else": { "$recursiveRef": "#" }, - "allOf": { "$ref": "#/$defs/schemaArray" }, - "anyOf": { "$ref": "#/$defs/schemaArray" }, - "oneOf": { "$ref": "#/$defs/schemaArray" }, - "not": { "$recursiveRef": "#" } - }, - "$defs": { "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$recursiveRef": "#" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/content.json -var require_content$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/content", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/content": true }, - "$recursiveAnchor": true, - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentMediaType": { "type": "string" }, - "contentEncoding": { "type": "string" }, - "contentSchema": { "$recursiveRef": "#" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/core.json -var require_core$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/core", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/core": true }, - "$recursiveAnchor": true, - "title": "Core vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "$id": { - "type": "string", - "format": "uri-reference", - "$comment": "Non-empty fragments not allowed.", - "pattern": "^[^#]*#?$" - }, - "$schema": { - "type": "string", - "format": "uri" - }, - "$anchor": { - "type": "string", - "pattern": "^[A-Za-z][-A-Za-z0-9.:_]*$" - }, - "$ref": { - "type": "string", - "format": "uri-reference" - }, - "$recursiveRef": { - "type": "string", - "format": "uri-reference" - }, - "$recursiveAnchor": { - "type": "boolean", - "default": false - }, - "$vocabulary": { - "type": "object", - "propertyNames": { - "type": "string", - "format": "uri" - }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$recursiveRef": "#" }, - "default": {} - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/format.json -var require_format = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/format", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/format": true }, - "$recursiveAnchor": true, - "title": "Format vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/meta-data.json -var require_meta_data$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/meta-data", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/meta-data": true }, - "$recursiveAnchor": true, - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/meta/validation.json -var require_validation$1 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2019-09/schema", - "$id": "https://json-schema.org/draft/2019-09/meta/validation", - "$vocabulary": { "https://json-schema.org/draft/2019-09/vocab/validation": true }, - "$recursiveAnchor": true, - "title": "Validation vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, - "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, - "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, - "minContains": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 1 - }, - "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, - "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/$defs/stringArray" }, - "dependentRequired": { - "type": "object", - "additionalProperties": { "$ref": "#/$defs/stringArray" } - }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] } - }, - "$defs": { - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 0 - }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2019-09/index.js -var require_json_schema_2019_09 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema$1(); - const applicator = require_applicator$1(); - const content = require_content$1(); - const core = require_core$1(); - const format = require_format(); - const metadata = require_meta_data$1(); - const validation = require_validation$1(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2019($data) { - [ - metaSchema, - applicator, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2019; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2019.js -var require__2019 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2019 = void 0; - const core_1 = require_core$3(); - const draft7_1 = require_draft7(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const discriminator_1 = require_discriminator(); - const json_schema_2019_09_1 = require_json_schema_2019_09(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2019-09/schema"; - var Ajv2019 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - this.addVocabulary(dynamic_1.default); - draft7_1.default.forEach((v) => this.addVocabulary(v)); - this.addVocabulary(next_1.default); - this.addVocabulary(unevaluated_1.default); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2019_09_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2019 = Ajv2019; - module.exports = exports = Ajv2019; - module.exports.Ajv2019 = Ajv2019; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2019; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/vocabularies/draft2020.js -var require_draft2020 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const core_1 = require_core$2(); - const validation_1 = require_validation$2(); - const applicator_1 = require_applicator$2(); - const dynamic_1 = require_dynamic(); - const next_1 = require_next(); - const unevaluated_1 = require_unevaluated$1(); - const format_1 = require_format$1(); - const metadata_1 = require_metadata(); - const draft2020Vocabularies = [ - dynamic_1.default, - core_1.default, - validation_1.default, - (0, applicator_1.default)(true), - format_1.default, - metadata_1.metadataVocabulary, - metadata_1.contentVocabulary, - next_1.default, - unevaluated_1.default - ]; - exports.default = draft2020Vocabularies; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/schema.json -var require_schema = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/schema", - "$vocabulary": { - "https://json-schema.org/draft/2020-12/vocab/core": true, - "https://json-schema.org/draft/2020-12/vocab/applicator": true, - "https://json-schema.org/draft/2020-12/vocab/unevaluated": true, - "https://json-schema.org/draft/2020-12/vocab/validation": true, - "https://json-schema.org/draft/2020-12/vocab/meta-data": true, - "https://json-schema.org/draft/2020-12/vocab/format-annotation": true, - "https://json-schema.org/draft/2020-12/vocab/content": true - }, - "$dynamicAnchor": "meta", - "title": "Core and Validation specifications meta-schema", - "allOf": [ - { "$ref": "meta/core" }, - { "$ref": "meta/applicator" }, - { "$ref": "meta/unevaluated" }, - { "$ref": "meta/validation" }, - { "$ref": "meta/meta-data" }, - { "$ref": "meta/format-annotation" }, - { "$ref": "meta/content" } - ], - "type": ["object", "boolean"], - "$comment": "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.", - "properties": { - "definitions": { - "$comment": "\"definitions\" has been replaced by \"$defs\".", - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "deprecated": true, - "default": {} - }, - "dependencies": { - "$comment": "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.", - "type": "object", - "additionalProperties": { "anyOf": [{ "$dynamicRef": "#meta" }, { "$ref": "meta/validation#/$defs/stringArray" }] }, - "deprecated": true, - "default": {} - }, - "$recursiveAnchor": { - "$comment": "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".", - "$ref": "meta/core#/$defs/anchorString", - "deprecated": true - }, - "$recursiveRef": { - "$comment": "\"$recursiveRef\" has been replaced by \"$dynamicRef\".", - "$ref": "meta/core#/$defs/uriReferenceString", - "deprecated": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/applicator.json -var require_applicator = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/applicator", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/applicator": true }, - "$dynamicAnchor": "meta", - "title": "Applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "prefixItems": { "$ref": "#/$defs/schemaArray" }, - "items": { "$dynamicRef": "#meta" }, - "contains": { "$dynamicRef": "#meta" }, - "additionalProperties": { "$dynamicRef": "#meta" }, - "properties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "patternProperties": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "propertyNames": { "format": "regex" }, - "default": {} - }, - "dependentSchemas": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" }, - "default": {} - }, - "propertyNames": { "$dynamicRef": "#meta" }, - "if": { "$dynamicRef": "#meta" }, - "then": { "$dynamicRef": "#meta" }, - "else": { "$dynamicRef": "#meta" }, - "allOf": { "$ref": "#/$defs/schemaArray" }, - "anyOf": { "$ref": "#/$defs/schemaArray" }, - "oneOf": { "$ref": "#/$defs/schemaArray" }, - "not": { "$dynamicRef": "#meta" } - }, - "$defs": { "schemaArray": { - "type": "array", - "minItems": 1, - "items": { "$dynamicRef": "#meta" } - } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/unevaluated.json -var require_unevaluated = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/unevaluated", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/unevaluated": true }, - "$dynamicAnchor": "meta", - "title": "Unevaluated applicator vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "unevaluatedItems": { "$dynamicRef": "#meta" }, - "unevaluatedProperties": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/content.json -var require_content = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/content", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/content": true }, - "$dynamicAnchor": "meta", - "title": "Content vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "contentEncoding": { "type": "string" }, - "contentMediaType": { "type": "string" }, - "contentSchema": { "$dynamicRef": "#meta" } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/core.json -var require_core = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/core", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/core": true }, - "$dynamicAnchor": "meta", - "title": "Core vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "$id": { - "$ref": "#/$defs/uriReferenceString", - "$comment": "Non-empty fragments not allowed.", - "pattern": "^[^#]*#?$" - }, - "$schema": { "$ref": "#/$defs/uriString" }, - "$ref": { "$ref": "#/$defs/uriReferenceString" }, - "$anchor": { "$ref": "#/$defs/anchorString" }, - "$dynamicRef": { "$ref": "#/$defs/uriReferenceString" }, - "$dynamicAnchor": { "$ref": "#/$defs/anchorString" }, - "$vocabulary": { - "type": "object", - "propertyNames": { "$ref": "#/$defs/uriString" }, - "additionalProperties": { "type": "boolean" } - }, - "$comment": { "type": "string" }, - "$defs": { - "type": "object", - "additionalProperties": { "$dynamicRef": "#meta" } - } - }, - "$defs": { - "anchorString": { - "type": "string", - "pattern": "^[A-Za-z_][-A-Za-z0-9._]*$" - }, - "uriString": { - "type": "string", - "format": "uri" - }, - "uriReferenceString": { - "type": "string", - "format": "uri-reference" - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/format-annotation.json -var require_format_annotation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/format-annotation", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/format-annotation": true }, - "$dynamicAnchor": "meta", - "title": "Format vocabulary meta-schema for annotation results", - "type": ["object", "boolean"], - "properties": { "format": { "type": "string" } } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/meta-data.json -var require_meta_data = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/meta-data", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/meta-data": true }, - "$dynamicAnchor": "meta", - "title": "Meta-data vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "title": { "type": "string" }, - "description": { "type": "string" }, - "default": true, - "deprecated": { - "type": "boolean", - "default": false - }, - "readOnly": { - "type": "boolean", - "default": false - }, - "writeOnly": { - "type": "boolean", - "default": false - }, - "examples": { - "type": "array", - "items": true - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/meta/validation.json -var require_validation = /* @__PURE__ */ __commonJSMin(((exports, module) => { - module.exports = { - "$schema": "https://json-schema.org/draft/2020-12/schema", - "$id": "https://json-schema.org/draft/2020-12/meta/validation", - "$vocabulary": { "https://json-schema.org/draft/2020-12/vocab/validation": true }, - "$dynamicAnchor": "meta", - "title": "Validation vocabulary meta-schema", - "type": ["object", "boolean"], - "properties": { - "type": { "anyOf": [{ "$ref": "#/$defs/simpleTypes" }, { - "type": "array", - "items": { "$ref": "#/$defs/simpleTypes" }, - "minItems": 1, - "uniqueItems": true - }] }, - "const": true, - "enum": { - "type": "array", - "items": true - }, - "multipleOf": { - "type": "number", - "exclusiveMinimum": 0 - }, - "maximum": { "type": "number" }, - "exclusiveMaximum": { "type": "number" }, - "minimum": { "type": "number" }, - "exclusiveMinimum": { "type": "number" }, - "maxLength": { "$ref": "#/$defs/nonNegativeInteger" }, - "minLength": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "pattern": { - "type": "string", - "format": "regex" - }, - "maxItems": { "$ref": "#/$defs/nonNegativeInteger" }, - "minItems": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "uniqueItems": { - "type": "boolean", - "default": false - }, - "maxContains": { "$ref": "#/$defs/nonNegativeInteger" }, - "minContains": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 1 - }, - "maxProperties": { "$ref": "#/$defs/nonNegativeInteger" }, - "minProperties": { "$ref": "#/$defs/nonNegativeIntegerDefault0" }, - "required": { "$ref": "#/$defs/stringArray" }, - "dependentRequired": { - "type": "object", - "additionalProperties": { "$ref": "#/$defs/stringArray" } - } - }, - "$defs": { - "nonNegativeInteger": { - "type": "integer", - "minimum": 0 - }, - "nonNegativeIntegerDefault0": { - "$ref": "#/$defs/nonNegativeInteger", - "default": 0 - }, - "simpleTypes": { "enum": [ - "array", - "boolean", - "integer", - "null", - "number", - "object", - "string" - ] }, - "stringArray": { - "type": "array", - "items": { "type": "string" }, - "uniqueItems": true, - "default": [] - } - } - }; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/refs/json-schema-2020-12/index.js -var require_json_schema_2020_12 = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const metaSchema = require_schema(); - const applicator = require_applicator(); - const unevaluated = require_unevaluated(); - const content = require_content(); - const core = require_core(); - const format = require_format_annotation(); - const metadata = require_meta_data(); - const validation = require_validation(); - const META_SUPPORT_DATA = ["/properties"]; - function addMetaSchema2020($data) { - [ - metaSchema, - applicator, - unevaluated, - content, - core, - with$data(this, format), - metadata, - with$data(this, validation) - ].forEach((sch) => this.addMetaSchema(sch, void 0, false)); - return this; - function with$data(ajv, sch) { - return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch; - } - } - exports.default = addMetaSchema2020; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv@8.18.0/node_modules/ajv/dist/2020.js -var require__2020 = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = void 0; - const core_1 = require_core$3(); - const draft2020_1 = require_draft2020(); - const discriminator_1 = require_discriminator(); - const json_schema_2020_12_1 = require_json_schema_2020_12(); - const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema"; - var Ajv2020 = class extends core_1.default { - constructor(opts = {}) { - super({ - ...opts, - dynamicRef: true, - next: true, - unevaluated: true - }); - } - _addVocabularies() { - super._addVocabularies(); - draft2020_1.default.forEach((v) => this.addVocabulary(v)); - if (this.opts.discriminator) this.addKeyword(discriminator_1.default); - } - _addDefaultMetaSchema() { - super._addDefaultMetaSchema(); - const { $data, meta } = this.opts; - if (!meta) return; - json_schema_2020_12_1.default.call(this, $data); - this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID; - } - defaultMeta() { - return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0); - } - }; - exports.Ajv2020 = Ajv2020; - module.exports = exports = Ajv2020; - module.exports.Ajv2020 = Ajv2020; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = Ajv2020; - var validate_1 = require_validate(); - Object.defineProperty(exports, "KeywordCxt", { - enumerable: true, - get: function() { - return validate_1.KeywordCxt; - } - }); - var codegen_1 = require_codegen(); - Object.defineProperty(exports, "_", { - enumerable: true, - get: function() { - return codegen_1._; - } - }); - Object.defineProperty(exports, "str", { - enumerable: true, - get: function() { - return codegen_1.str; - } - }); - Object.defineProperty(exports, "stringify", { - enumerable: true, - get: function() { - return codegen_1.stringify; - } - }); - Object.defineProperty(exports, "nil", { - enumerable: true, - get: function() { - return codegen_1.nil; - } - }); - Object.defineProperty(exports, "Name", { - enumerable: true, - get: function() { - return codegen_1.Name; - } - }); - Object.defineProperty(exports, "CodeGen", { - enumerable: true, - get: function() { - return codegen_1.CodeGen; - } - }); - var validation_error_1 = require_validation_error(); - Object.defineProperty(exports, "ValidationError", { - enumerable: true, - get: function() { - return validation_error_1.default; - } - }); - var ref_error_1 = require_ref_error(); - Object.defineProperty(exports, "MissingRefError", { - enumerable: true, - get: function() { - return ref_error_1.default; - } - }); -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/formats.js -var require_formats = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatNames = exports.fastFormats = exports.fullFormats = void 0; - function fmtDef(validate, compare) { - return { - validate, - compare - }; - } - exports.fullFormats = { - date: fmtDef(date, compareDate), - time: fmtDef(getTime(true), compareTime), - "date-time": fmtDef(getDateTime(true), compareDateTime), - "iso-time": fmtDef(getTime(), compareIsoTime), - "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime), - duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, - uri, - "uri-reference": /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i, - "uri-template": /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i, - url: /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu, - email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i, - hostname: /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i, - ipv4: /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/, - ipv6: /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i, - regex, - uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i, - "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/, - "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i, - "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/, - byte, - int32: { - type: "number", - validate: validateInt32 - }, - int64: { - type: "number", - validate: validateInt64 - }, - float: { - type: "number", - validate: validateNumber - }, - double: { - type: "number", - validate: validateNumber - }, - password: true, - binary: true - }; - exports.fastFormats = { - ...exports.fullFormats, - date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate), - time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime), - "date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareDateTime), - "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime), - "iso-date-time": fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoDateTime), - uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i, - "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i, - email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i - }; - exports.formatNames = Object.keys(exports.fullFormats); - function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); - } - const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; - const DAYS = [ - 0, - 31, - 28, - 31, - 30, - 31, - 30, - 31, - 31, - 30, - 31, - 30, - 31 - ]; - function date(str) { - const matches = DATE.exec(str); - if (!matches) return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]); - } - function compareDate(d1, d2) { - if (!(d1 && d2)) return void 0; - if (d1 > d2) return 1; - if (d1 < d2) return -1; - return 0; - } - const TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i; - function getTime(strictTimeZone) { - return function time(str) { - const matches = TIME.exec(str); - if (!matches) return false; - const hr = +matches[1]; - const min = +matches[2]; - const sec = +matches[3]; - const tz = matches[4]; - const tzSign = matches[5] === "-" ? -1 : 1; - const tzH = +(matches[6] || 0); - const tzM = +(matches[7] || 0); - if (tzH > 23 || tzM > 59 || strictTimeZone && !tz) return false; - if (hr <= 23 && min <= 59 && sec < 60) return true; - const utcMin = min - tzM * tzSign; - const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0); - return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61; - }; - } - function compareTime(s1, s2) { - if (!(s1 && s2)) return void 0; - const t1 = (/* @__PURE__ */ new Date("2020-01-01T" + s1)).valueOf(); - const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s2)).valueOf(); - if (!(t1 && t2)) return void 0; - return t1 - t2; - } - function compareIsoTime(t1, t2) { - if (!(t1 && t2)) return void 0; - const a1 = TIME.exec(t1); - const a2 = TIME.exec(t2); - if (!(a1 && a2)) return void 0; - t1 = a1[1] + a1[2] + a1[3]; - t2 = a2[1] + a2[2] + a2[3]; - if (t1 > t2) return 1; - if (t1 < t2) return -1; - return 0; - } - const DATE_TIME_SEPARATOR = /t|\s/i; - function getDateTime(strictTimeZone) { - const time = getTime(strictTimeZone); - return function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length === 2 && date(dateTime[0]) && time(dateTime[1]); - }; - } - function compareDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const d1 = new Date(dt1).valueOf(); - const d2 = new Date(dt2).valueOf(); - if (!(d1 && d2)) return void 0; - return d1 - d2; - } - function compareIsoDateTime(dt1, dt2) { - if (!(dt1 && dt2)) return void 0; - const [d1, t1] = dt1.split(DATE_TIME_SEPARATOR); - const [d2, t2] = dt2.split(DATE_TIME_SEPARATOR); - const res = compareDate(d1, d2); - if (res === void 0) return void 0; - return res || compareTime(t1, t2); - } - const NOT_URI_FRAGMENT = /\/|:/; - const URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; - function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI.test(str); - } - const BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm; - function byte(str) { - BYTE.lastIndex = 0; - return BYTE.test(str); - } - const MIN_INT32 = -(2 ** 31); - const MAX_INT32 = 2 ** 31 - 1; - function validateInt32(value) { - return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32; - } - function validateInt64(value) { - return Number.isInteger(value); - } - function validateNumber() { - return true; - } - const Z_ANCHOR = /[^\\]\\Z/; - function regex(str) { - if (Z_ANCHOR.test(str)) return false; - try { - new RegExp(str); - return true; - } catch (e) { - return false; - } - } -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/limit.js -var require_limit = /* @__PURE__ */ __commonJSMin(((exports) => { - Object.defineProperty(exports, "__esModule", { value: true }); - exports.formatLimitDefinition = void 0; - const ajv_1 = require_ajv(); - const codegen_1 = require_codegen(); - const ops = codegen_1.operators; - const KWDs = { - formatMaximum: { - okStr: "<=", - ok: ops.LTE, - fail: ops.GT - }, - formatMinimum: { - okStr: ">=", - ok: ops.GTE, - fail: ops.LT - }, - formatExclusiveMaximum: { - okStr: "<", - ok: ops.LT, - fail: ops.GTE - }, - formatExclusiveMinimum: { - okStr: ">", - ok: ops.GT, - fail: ops.LTE - } - }; - const error = { - message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`, - params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}` - }; - exports.formatLimitDefinition = { - keyword: Object.keys(KWDs), - type: "string", - schemaType: "string", - $data: true, - error, - code(cxt) { - const { gen, data, schemaCode, keyword, it } = cxt; - const { opts, self } = it; - if (!opts.validateFormats) return; - const fCxt = new ajv_1.KeywordCxt(it, self.RULES.all.format.definition, "format"); - if (fCxt.$data) validate$DataFormat(); - else validateFormat(); - function validate$DataFormat() { - const fmts = gen.scopeValue("formats", { - ref: self.formats, - code: opts.code.formats - }); - const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`); - cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt))); - } - function validateFormat() { - const format = fCxt.schema; - const fmtDef = self.formats[format]; - if (!fmtDef || fmtDef === true) return; - if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") throw new Error(`"${keyword}": format "${format}" does not define "compare" function`); - const fmt = gen.scopeValue("formats", { - key: format, - ref: fmtDef, - code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0 - }); - cxt.fail$data(compareCode(fmt)); - } - function compareCode(fmt) { - return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`; - } - }, - dependencies: ["format"] - }; - const formatLimitPlugin = (ajv) => { - ajv.addKeyword(exports.formatLimitDefinition); - return ajv; - }; - exports.default = formatLimitPlugin; -})); - -//#endregion -//#region ../../node_modules/.pnpm/ajv-formats@3.0.1_ajv@8.18.0/node_modules/ajv-formats/dist/index.js -var require_dist = /* @__PURE__ */ __commonJSMin(((exports, module) => { - Object.defineProperty(exports, "__esModule", { value: true }); - const formats_1 = require_formats(); - const limit_1 = require_limit(); - const codegen_1 = require_codegen(); - const fullName = new codegen_1.Name("fullFormats"); - const fastName = new codegen_1.Name("fastFormats"); - const formatsPlugin = (ajv, opts = { keywords: true }) => { - if (Array.isArray(opts)) { - addFormats(ajv, opts, formats_1.fullFormats, fullName); - return ajv; - } - const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName]; - addFormats(ajv, opts.formats || formats_1.formatNames, formats, exportName); - if (opts.keywords) (0, limit_1.default)(ajv); - return ajv; - }; - formatsPlugin.get = (name, mode = "full") => { - const f = (mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats)[name]; - if (!f) throw new Error(`Unknown format "${name}"`); - return f; - }; - function addFormats(ajv, list, fs, exportName) { - var _a; - var _b; - (_a = (_b = ajv.opts.code).formats) !== null && _a !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) ajv.addFormat(f, fs[f]); - } - module.exports = exports = formatsPlugin; - Object.defineProperty(exports, "__esModule", { value: true }); - exports.default = formatsPlugin; -})); - -//#endregion -//#region ../core-internal/src/validators/ajvProvider.ts -var import_ajv = require_ajv(); -var import__2019 = require__2019(); -var import__2020 = require__2020(); -var import_dist = /* @__PURE__ */ __toESM(require_dist(), 1); -/** `ajv-formats` default export, normalised through the CJS/ESM interop wrapper. */ -const ajvProvider_CEoC_sr_addFormats = import_dist.default; -function createDefaultAjvInstance(engineClass) { - const ajv = new engineClass({ - strict: false, - validateFormats: true, - validateSchema: false, - allErrors: true - }); - ajvProvider_CEoC_sr_addFormats(ajv); - return ajv; -} -/** -* AJV-backed JSON Schema validator. See `@modelcontextprotocol/{client,server}/validators/ajv` -* for the customisation entry point (re-exports `Ajv` and `addFormats` from the bundled copy). -* -* Default dispatches on the schema's declared dialect: no `$schema` or 2020-12 → `Ajv2020` -* (SEP-1613); 2019-09 → `Ajv2019`; draft-07 or draft-06 → the classic draft-07 `Ajv` class -* (draft-07's changes over draft-06 are additive, so one engine covers both). Known draft-07 deviation: classic Ajv -* evaluates keywords adjacent to `$ref` (stricter than draft-07's ignore-siblings rule, matching -* v1's default engine), while the cfworker provider ignores them per spec. -* Schemas declaring any other `$schema` are -* rejected with a plain `Error`; pass a pre-configured Ajv instance to validate -* other dialects. The SDK bundles ajv internally but does not re-export `Ajv2020` (its type -* graph tips downstream declaration bundling — see #2339). To construct a custom 2020-12 -* instance, add `ajv` to your own dependencies (matching the SDK's pinned version) and -* `import { Ajv2020 } from 'ajv/dist/2020.js'` — `new Ajv(...)` is the draft-07 class and would -* silently downgrade dialect. -* -* @example Use with default configuration -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_default" -* const validator = new AjvJsonSchemaValidator(); -* ``` -* -* @example Use with a custom AJV instance -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_customInstance" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -* -* @example Register ajv-formats -* ```ts source="./ajvProvider.examples.ts#AjvJsonSchemaValidator_withFormats" -* // import { Ajv2020 } from 'ajv/dist/2020.js'; -* const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* const validator = new AjvJsonSchemaValidator(ajv); -* ``` -*/ -var AjvJsonSchemaValidator = class { - _ajv; - /** Lazy classic (draft-07) engine, built on the first draft-07/draft-06-declared schema. */ - _ajvDraft7; - /** Lazy 2019-09 engine, built on the first 2019-09-declared schema. */ - _ajv2019; - /** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */ - _userAjv; - /** - * @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is - * used for **every** schema regardless of its declared `$schema` (the caller owns dialect - * choice). When omitted, the provider constructs per-dialect engines (`Ajv2020`, `Ajv2019`, - * and the classic draft-07 `Ajv` for draft-07/06-declared schemas) with - * `strict: false`, `validateFormats: true`, `validateSchema: false`, `allErrors: true`, and - * `ajv-formats` registered — **lazily, on the first {@linkcode getValidator} call needing each**, so - * constructing the provider (e.g. as the default validator of a `Client`/`Server` that never - * validates a JSON Schema) does not pay the ajv + ajv-formats instantiation cost. The parameter - * is typed structurally so consumers who don't pass an instance need not have `ajv` installed. - */ - constructor(ajv) { - this._userAjv = ajv !== void 0; - this._ajv = ajv; - } - /** The underlying 2020-12 engine — the default instance is created on first use. */ - get ajv() { - return this._ajv ??= createDefaultAjvInstance(import__2020.Ajv2020); - } - /** - * Pick the engine for a schema's declared dialect. A caller-supplied engine is used for - * every schema — do not second-guess by `$schema` (bring-your-own-validator means - * bring-your-own-dialect). Otherwise: no `$schema` or 2020-12 → `Ajv2020`; 2019-09 → - * `Ajv2019`; draft-07 or draft-06 → classic `Ajv`; anything else → `Error`. - */ - _engineFor(schema) { - if (this._userAjv) return this.ajv; - const dialect = declaredDialect(schema, "pass a pre-configured Ajv instance to AjvJsonSchemaValidator(ajv) to validate other dialects."); - if (dialect === "2020-12") return this.ajv; - if (dialect === "2019-09") return this._ajv2019 ??= createDefaultAjvInstance(import__2019.Ajv2019); - return this._ajvDraft7 ??= createDefaultAjvInstance(import_ajv.Ajv); - } - getValidator(schema) { - const engine = this._engineFor(schema); - const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? engine.getSchema(schema.$id) ?? engine.compile(schema) : engine.compile(schema); - return (input) => { - return ajvValidator(input) ? { - valid: true, - data: input, - errorMessage: void 0 - } : { - valid: false, - data: void 0, - errorMessage: engine.errorsText(ajvValidator.errors) - }; - }; - } -}; -/** -* Draft-07 AJV class, re-exported for consumers who need to opt back to the pre-SEP-1613 default. -* The full v1-equivalent construction is: -* -* ```ts -* const ajv = new Ajv({ strict: false, validateFormats: true, validateSchema: false, allErrors: true }); -* addFormats(ajv); -* new AjvJsonSchemaValidator(ajv); -* ``` -* -* (omitting `validateSchema: false` makes a 2020-12-stamped `$schema` fail with an opaque -* "no schema with key or ref …" engine error; omitting `addFormats` silently drops `format` -* validation that the v1 default had). -* -* The SDK bundles ajv internally but does not re-export `Ajv2020` (its type graph tips downstream -* declaration bundling — see #2339). To construct a custom 2020-12 instance, add `ajv` to your own -* dependencies (matching the SDK's pinned version) and `import { Ajv2020 } from 'ajv/dist/2020.js'`. -*/ -const ajvProvider_CEoC_sr_Ajv = import_ajv.Ajv; - -//#endregion - -//# sourceMappingURL=ajvProvider-CEoC__sr.mjs.map - - - - - - - - -//#region src/server/completable.ts -const COMPLETABLE_SYMBOL = Symbol.for("mcp.completable"); -/** -* Wraps a schema to provide autocompletion capabilities. Useful for, e.g., prompt arguments in MCP. -* -* @example -* ```ts source="./completable.examples.ts#completable_basicUsage" -* server.registerPrompt( -* 'review-code', -* { -* title: 'Code Review', -* argsSchema: z.object({ -* language: completable(z.string().describe('Programming language'), value => -* ['typescript', 'javascript', 'python', 'rust', 'go'].filter(lang => lang.startsWith(value)) -* ) -* }) -* }, -* ({ language }) => ({ -* messages: [ -* { -* role: 'user' as const, -* content: { -* type: 'text' as const, -* text: `Review this ${language} code.` -* } -* } -* ] -* }) -* ); -* ``` -* -* @see {@linkcode server/mcp.McpServer.registerPrompt | McpServer.registerPrompt} for using completable schemas in prompt argument definitions -*/ -function completable(schema, complete) { - Object.defineProperty(schema, COMPLETABLE_SYMBOL, { - value: { complete }, - enumerable: false, - writable: false, - configurable: false - }); - return schema; -} -/** -* Checks if a schema is completable (has completion metadata). -*/ -function isCompletable(schema) { - return !!schema && typeof schema === "object" && COMPLETABLE_SYMBOL in schema; -} -/** -* Gets the completer callback from a completable schema, if it exists. -*/ -function getCompleter(schema) { - return schema[COMPLETABLE_SYMBOL]?.complete; -} - -//#endregion -//#region src/server/sseKeepAlive.ts -/** Default interval between SSE keep-alive comment frames. */ -const mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS = 15e3; -const MAX_TIMER_DELAY_MS = (/* unused pure expression or super */ null && (2 ** 31 - 1)); -/** Arms an unref'd timer, or disables keep-alive for invalid delays. */ -function mcp_DXXb3Vv3_armSseKeepAlive(intervalMs, onTick) { - if (!Number.isFinite(intervalMs) || intervalMs < 1) return; - const timer = setInterval(onTick, Math.min(intervalMs, MAX_TIMER_DELAY_MS)); - timer.unref?.(); - return timer; -} - -//#endregion -//#region src/server/serverEventBus.ts -/** -* A `ServerEventBus` backed by an in-process listener set. -* -* `publish()` delivers synchronously to the live listener set (a listener -* unsubscribing itself mid-dispatch is safe; the entry's listen-router -* listeners never unsubscribe peers). A throwing listener does not stop -* delivery to the others. -*/ -var mcp_DXXb3Vv3_InMemoryServerEventBus = class { - _listeners = /* @__PURE__ */ new Set(); - /** - * @param onerror - Optional callback for errors thrown by listeners - * during dispatch. - */ - constructor(onerror) { - this.onerror = onerror; - } - publish(event) { - for (const listener of this._listeners) try { - listener(event); - } catch (error) { - this.onerror?.(error instanceof Error ? error : new Error(String(error))); - } - } - subscribe(listener) { - this._listeners.add(listener); - let live = true; - return () => { - if (!live) return; - live = false; - this._listeners.delete(listener); - }; - } - /** The number of currently registered listeners (test/introspection only — the routers track capacity via their own open-subscription set). */ - get listenerCount() { - return this._listeners.size; - } -}; -/** Build a {@linkcode ServerNotifier} over a bus. */ -function mcp_DXXb3Vv3_createServerNotifier(bus) { - return { - toolsChanged: () => bus.publish({ kind: "tools_list_changed" }), - promptsChanged: () => bus.publish({ kind: "prompts_list_changed" }), - resourcesChanged: () => bus.publish({ kind: "resources_list_changed" }), - resourceUpdated: (uri) => bus.publish({ - kind: "resource_updated", - uri - }) - }; -} -/** -* Whether a `subscriptions/listen` filter accepts a given change event. -* -* Pure: no I/O, no mutation. The filter governs ONLY the four -* subscription-gated change types — non-gated notifications never reach the -* bus and are not modeled here. -* -* `resource_updated` matches only when `resourceSubscriptions` is present and -* contains the event's URI exactly (per the spec: "for these resource URIs"). -*/ -function listenFilterAccepts(filter, event) { - switch (event.kind) { - case "tools_list_changed": return filter.toolsListChanged === true; - case "prompts_list_changed": return filter.promptsListChanged === true; - case "resources_list_changed": return filter.resourcesListChanged === true; - case "resource_updated": return filter.resourceSubscriptions !== void 0 && filter.resourceSubscriptions.includes(event.uri); - } -} -/** -* The honored subset of a requested filter: keeps only the fields the client -* explicitly opted in to (drops `false` and absent fields), narrowed against -* the server's declared capabilities when supplied. The serving entry sends -* this back in `notifications/subscriptions/acknowledged` so the ack reflects -* what the server can actually deliver. -* -* - `toolsListChanged` is honored only when `capabilities.tools.listChanged` -* is advertised; likewise `promptsListChanged` / `resourcesListChanged`. -* - `resourceSubscriptions` is honored only when -* `capabilities.resources.subscribe` is advertised. -* -* `capabilities` is optional on this pure helper for test convenience only — -* both wired routers REQUIRE capabilities at the call site (the HTTP router's -* `serve()` takes a required parameter; `StdioListenRouter.serve()` throws -* before `setServerCapabilities()` was called), so the fail-open -* `undefined → honor everything` branch is never reachable on a wired entry. -*/ -function honoredSubset(requested, capabilities) { - const honored = {}; - const allow = (bit) => capabilities === void 0 || bit === true; - if (requested.toolsListChanged === true && allow(capabilities?.tools?.listChanged)) honored.toolsListChanged = true; - if (requested.promptsListChanged === true && allow(capabilities?.prompts?.listChanged)) honored.promptsListChanged = true; - if (requested.resourcesListChanged === true && allow(capabilities?.resources?.listChanged)) honored.resourcesListChanged = true; - if (requested.resourceSubscriptions !== void 0 && requested.resourceSubscriptions.length > 0 && allow(capabilities?.resources?.subscribe)) honored.resourceSubscriptions = [...requested.resourceSubscriptions]; - return honored; -} -/** Map a {@linkcode ServerEvent} onto its wire notification `{method, params}`. */ -function serverEventToNotification(event) { - switch (event.kind) { - case "tools_list_changed": return { method: "notifications/tools/list_changed" }; - case "prompts_list_changed": return { method: "notifications/prompts/list_changed" }; - case "resources_list_changed": return { method: "notifications/resources/list_changed" }; - case "resource_updated": return { - method: "notifications/resources/updated", - params: { uri: event.uri } - }; - } -} - -//#endregion -//#region src/server/listenRouter.ts -/** Default capacity guard: refuse a new subscription when this many are already open. */ -const mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS = 1024; -function jsonRpcError(id, code, message) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message - }, - id - }, { status: 200 }); -} -/** Stamp the subscription id onto a notification's `_meta`. Non-mutating. */ -function stampSubscriptionId(notification, subscriptionId) { - return { - method: notification.method, - params: { - ...notification.params, - _meta: { - ...notification.params?._meta, - [SUBSCRIPTION_ID_META_KEY]: subscriptionId - } - } - }; -} -/** -* Read the requested filter off a `subscriptions/listen` request body. -* Returns the validated filter, or `undefined` when `params.notifications` -* is absent or fails the schema (the caller answers `-32602` — the spec -* marks `notifications` REQUIRED on the listen request). -*/ -function parseListenFilter(message) { - const outcome = codecForVersion(MODERN_WIRE_REVISION).validateRequest("subscriptions/listen", message); - return outcome.ok ? outcome.value.params?.notifications : void 0; -} -function mcp_DXXb3Vv3_createListenRouter(options) { - const { bus, onerror } = options; - const maxSubscriptions = options.maxSubscriptions ?? mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS; - const keepAliveMs = options.keepAliveMs ?? mcp_DXXb3Vv3_DEFAULT_SSE_KEEP_ALIVE_MS; - const open = /* @__PURE__ */ new Set(); - function serve(message, signal, capabilities, serverInfo) { - if (open.size >= maxSubscriptions) { - onerror?.(/* @__PURE__ */ new Error(`subscriptions/listen refused: subscription limit reached (${maxSubscriptions})`)); - return jsonRpcError(message.id, -32603, "Subscription limit reached"); - } - const filter = parseListenFilter(message); - if (filter === void 0) return jsonRpcError(message.id, -32602, "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter"); - const honored = honoredSubset(filter, capabilities); - const subscriptionId = message.id; - const encoder = new TextEncoder(); - let controller; - let closed = false; - let unsubscribe; - let keepAliveTimer; - let abortCleanup; - const writeFrame = (frame) => { - if (closed) return; - try { - controller.enqueue(encoder.encode(frame)); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - }; - const writeNotification = (method, params) => { - writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - method, - params - })}\n\n`); - }; - const teardown = (graceful) => { - if (closed) return; - if (graceful) writeFrame(`event: message\ndata: ${JSON.stringify({ - jsonrpc: "2.0", - id: subscriptionId, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: subscriptionId, - [SERVER_INFO_META_KEY]: serverInfo - } - } - })}\n\n`); - closed = true; - try { - unsubscribe?.(); - } catch (error) { - onerror?.(error instanceof Error ? error : new Error(String(error))); - } - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - abortCleanup?.(); - open.delete(teardown); - try { - controller.close(); - } catch {} - }; - const readable = new ReadableStream({ - start(streamController) { - controller = streamController; - const ack = stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, subscriptionId); - writeNotification(ack.method, ack.params); - unsubscribe = bus.subscribe((event) => { - if (closed || !listenFilterAccepts(honored, event)) return; - const note = stampSubscriptionId(serverEventToNotification(event), subscriptionId); - writeNotification(note.method, note.params); - }); - keepAliveTimer = mcp_DXXb3Vv3_armSseKeepAlive(keepAliveMs, () => writeFrame(": keepalive\n\n")); - open.add(teardown); - }, - cancel() { - teardown(false); - } - }); - if (signal !== void 0) if (signal.aborted) teardown(false); - else { - const onAbort = () => teardown(false); - signal.addEventListener("abort", onAbort, { once: true }); - abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - return new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - }); - } - return { - serve, - closeAll() { - for (const teardown of open) teardown(true); - }, - get openCount() { - return open.size; - } - }; -} -const CHANGE_NOTIFICATION_METHODS = new Set([ - "notifications/tools/list_changed", - "notifications/prompts/list_changed", - "notifications/resources/list_changed", - "notifications/resources/updated" -]); -/** -* Per-connection listen state for the stdio entry. One instance is held by -* `serveStdio` for the connection lifetime; it routes inbound -* `subscriptions/listen` / `notifications/cancelled` and rewrites outbound -* change notifications onto the active subscriptions. No bus — the long-lived -* pinned instance's existing `send*ListChanged()` calls feed straight into -* `routeOutbound()`. -*/ -var mcp_DXXb3Vv3_StdioListenRouter = class { - /** Active subscriptions, keyed by the listen request's JSON-RPC id verbatim. */ - _subs = /* @__PURE__ */ new Map(); - /** - * The serving instance's declared capabilities. Filled in by the entry - * once the modern instance is constructed (the router is created before - * the instance exists), so the acknowledged filter is narrowed against - * what the server can actually deliver. - */ - _serverCapabilities; - /** - * The serving instance's identity, stamped onto the graceful-close - * results' `_meta` (the spec's `SubscriptionsListenResultMeta` extends - * `ResultMetaObject`). Handed over together with the capabilities. - */ - _serverInfo; - constructor(_maxSubscriptions = mcp_DXXb3Vv3_DEFAULT_MAX_SUBSCRIPTIONS, serverCapabilities, serverInfo) { - this._maxSubscriptions = _maxSubscriptions; - this._serverCapabilities = serverCapabilities; - this._serverInfo = serverInfo; - } - /** - * Record the serving instance's declared capabilities and identity once - * it has been constructed. Called by `serveStdio`'s connect path; - * subsequent `serve()` calls narrow the honored filter against the - * capabilities, and `teardownAll()` stamps the identity. - */ - setServerCapabilities(capabilities, serverInfo) { - this._serverCapabilities = capabilities; - if (serverInfo !== void 0) this._serverInfo = serverInfo; - } - /** Whether `id` is an active listen subscription on this connection. */ - has(id) { - return this._subs.has(id); - } - /** - * Serve one inbound `subscriptions/listen` request: registers the - * subscription and returns the stamped acknowledged notification (or, on - * capacity / params rejection, the in-band JSON-RPC error response). - * - * @throws when called before {@linkcode setServerCapabilities} (or the - * constructor) has supplied the serving instance's capabilities. Honoring a - * filter without knowing the server's advertised capabilities would fail - * open (deliver unadvertised types); the entry guarantees capabilities are - * set before any listen request is routed here. - */ - serve(message) { - if (this._serverCapabilities === void 0) throw new Error("StdioListenRouter.serve() called before setServerCapabilities(); refusing to honor a filter without capabilities"); - if (this._subs.size >= this._maxSubscriptions) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32603, - message: "Subscription limit reached" - } - }; - const filter = parseListenFilter(message); - if (filter === void 0) return { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: "Invalid params: 'notifications' is required and must be a valid SubscriptionFilter" - } - }; - const honored = honoredSubset(filter, this._serverCapabilities); - this._subs.set(message.id, honored); - return stampSubscriptionId({ - method: "notifications/subscriptions/acknowledged", - params: { notifications: honored } - }, message.id); - } - /** - * Tear down one subscription (inbound `notifications/cancelled`). Returns - * `true` when a subscription was removed. After this call NOTHING further - * is delivered for that subscription id (the post-cancel hardening). - */ - cancel(id) { - return this._subs.delete(id); - } - /** - * Route an outbound notification through the active subscriptions. - * - * - For a subscription-gated change notification, returns one stamped copy - * per subscription that opted in to it (an empty array means it is - * dropped — the modern era never delivers an un-requested change type). - * - For any other outbound message, returns `'passthrough'` (the entry - * forwards it as-is). - */ - routeOutbound(message) { - if (!CHANGE_NOTIFICATION_METHODS.has(message.method)) return "passthrough"; - const uriParam = message.params?.["uri"]; - const uri = typeof uriParam === "string" ? uriParam : void 0; - const event = notificationToServerEvent(message.method, uri); - const out = []; - for (const [subscriptionId, filter] of this._subs) if (listenFilterAccepts(filter, event)) out.push(stampSubscriptionId({ - method: message.method, - params: message.params ?? {} - }, subscriptionId)); - return out; - } - /** - * Server-side graceful teardown of every active subscription: returns the - * empty `subscriptions/listen` JSON-RPC result for each subscription id — - * the spec's graceful-close signal, `_meta` carrying the subscription id - * and the serving instance's identity — for the entry to emit before - * closing the wire. Clears the set so nothing further is delivered. - */ - teardownAll() { - const out = []; - for (const id of this._subs.keys()) out.push({ - jsonrpc: "2.0", - id, - result: { - resultType: "complete", - _meta: { - [SUBSCRIPTION_ID_META_KEY]: id, - ...this._serverInfo !== void 0 && { [SERVER_INFO_META_KEY]: this._serverInfo } - } - } - }); - this._subs.clear(); - return out; - } -}; -function notificationToServerEvent(method, uri) { - switch (method) { - case "notifications/tools/list_changed": return { kind: "tools_list_changed" }; - case "notifications/prompts/list_changed": return { kind: "prompts_list_changed" }; - case "notifications/resources/list_changed": return { kind: "resources_list_changed" }; - default: return { - kind: "resource_updated", - uri: uri ?? "" - }; - } -} - -//#endregion -//#region src/server/legacyInputRequiredShim.ts -/** -* Default handler re-entries per originating request — tighter than the -* client driver's 10 because the shim holds a live wire request open. -*/ -const DEFAULT_LEGACY_SHIM_MAX_ROUNDS = 8; -/** Default per-leg timeout: legs are human-paced, so the 60s protocol default is wrong. */ -const DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS = 6e5; -/** Resolves and validates `ServerOptions.inputRequired`, failing loudly at construction time. */ -function resolveLegacyShimOptions(options) { - if (options?.maxRounds !== void 0 && (!Number.isInteger(options.maxRounds) || options.maxRounds < 1)) throw new RangeError(`inputRequired.maxRounds must be a positive integer (got ${options.maxRounds})`); - if (options?.roundTimeoutMs !== void 0 && (!Number.isFinite(options.roundTimeoutMs) || options.roundTimeoutMs <= 0)) throw new RangeError(`inputRequired.roundTimeoutMs must be a positive number (got ${options.roundTimeoutMs})`); - return { - maxRounds: options?.maxRounds ?? DEFAULT_LEGACY_SHIM_MAX_ROUNDS, - roundTimeoutMs: options?.roundTimeoutMs ?? DEFAULT_LEGACY_SHIM_ROUND_TIMEOUT_MS, - legacyShim: options?.legacyShim ?? true - }; -} -/** -* Validates one `inputRequests` entry: malformed or unknown kinds are server -* bugs and fail loudly on both eras. Shared by the modern seam's capability -* check and the shim's gate. -*/ -function coerceEmbeddedInputRequest(method, key, entry) { - if (entry === null || typeof entry !== "object" || typeof entry.method !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an invalid input request '${key}': each inputRequests entry must be an embedded elicitation/create, sampling/createMessage, or roots/list request`); - const embedded = entry; - const required = requiredClientCapabilitiesForInputRequest(embedded); - if (required === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}', which is not an embedded request the 2026-07-28 revision defines`); - return { - embedded, - required - }; -} -/** -* The 2025-11-25 URL-mode wire shape requires an `elicitationId`; the 2026 -* in-band shape has none, so URL legs mint one (CSPRNG-backed, with a -* getRandomValues fallback for runtimes without `randomUUID`). -*/ -function syntheticElicitationId() { - const webCrypto = globalThis.crypto; - if (webCrypto?.randomUUID !== void 0) return webCrypto.randomUUID(); - const bytes = new Uint8Array(16); - webCrypto.getRandomValues(bytes); - bytes[6] = bytes[6] & 15 | 64; - bytes[8] = bytes[8] & 63 | 128; - const hex = [...bytes].map((byte) => byte.toString(16).padStart(2, "0")).join(""); - return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; -} -/** Per-family surfacing: tools/call → isError result (the 2025 idiom); prompts/resources → JSON-RPC error. */ -function legacyShimFailure(method, message) { - if (method === "tools/call") return { - content: [{ - type: "text", - text: message - }], - isError: true - }; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, message); -} -/** The fulfilment loop — see the module doc for the contract. */ -var LegacyInputRequiredShim = class { - constructor(_host) { - this._host = _host; - } - async fulfill(method, handler, request, ctx, firstResult) { - const { maxRounds, roundTimeoutMs } = this._host; - const outerSignal = ctx.mcpReq.signal; - let current = firstResult; - let round = 0; - while (true) { - round += 1; - if (round > maxRounds) return legacyShimFailure(method, inputRequiredRoundsExceededMessage(method, maxRounds)); - const inputRequests = current.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const requestState = typeof current.requestState === "string" ? current.requestState : void 0; - if (!hasInputRequests && requestState === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - let responses; - if (hasInputRequests) { - const declared = this._host.resolvedClientCapabilities(ctx); - const coerced = []; - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - if (embedded.method !== "roots/list" && embedded.params === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input request '${key}' of kind '${embedded.method}' without params`); - if (src_CX2iR2pK_missingClientCapabilities(required, declared) !== void 0) return legacyShimFailure(method, `Cannot request input '${key}' (${embedded.method}): the client on this 2025-era connection did not declare the required capability${declared === void 0 ? " (no client capabilities are available on this connection — per-request legacy serving cannot receive server-to-client requests)" : ""}`); - coerced.push([key, embedded]); - } - const roundAbort = linkedRoundAbort(outerSignal); - try { - const legOptions = { - relatedRequestId: ctx.mcpReq.id, - timeout: roundTimeoutMs, - resetTimeoutOnProgress: true, - onprogress: () => {}, - signal: roundAbort.signal - }; - const fulfilled = await Promise.all(coerced.map(async ([key, embedded]) => { - try { - return [key, await this._dispatchLeg(embedded, legOptions)]; - } catch (error) { - roundAbort.abort(error); - throw error; - } - })); - responses = Object.fromEntries(fulfilled); - } catch (error) { - if (outerSignal.aborted) throw error; - return legacyShimFailure(method, `Fulfilling input required by '${method}' failed: ${error instanceof Error ? error.message : String(error)}`); - } finally { - roundAbort.dispose(); - } - } else await sleep((/* inlined export .C */250), outerSignal); - let ctxNext = { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - inputResponses: responses, - droppedInputResponseKeys: void 0, - requestState: requestStateAccessor(requestState) - } - }; - if (requestState !== void 0) { - const decoded = await this._host.verifyRequestState(requestState, ctxNext, method); - if (decoded !== void 0) ctxNext = withRequestStateValue(ctxNext, decoded); - } - const next = await handler(request, ctxNext); - if (!isInputRequiredResult(next)) return next; - current = next; - } - } - /** Routes one embedded request through the host's existing 2025-era senders (gate already ran). */ - async _dispatchLeg(embedded, options) { - switch (embedded.method) { - case "elicitation/create": { - let params = embedded.params; - if (params.mode === "url" && params.elicitationId === void 0) params = { - ...params, - elicitationId: syntheticElicitationId() - }; - return await this._host.sendElicitation(params, options); - } - case "sampling/createMessage": return await this._host.sendSampling(embedded.params, options); - case "roots/list": return await this._host.listRoots(embedded.params, options); - } - } -}; - -//#endregion -//#region src/server/server.ts -/** -* The request methods whose 2026-07-28 result vocabulary includes -* `input_required` (the multi round-trip methods). Returning an -* input-required result from any other handler is a server bug. -*/ -const INPUT_REQUIRED_CAPABLE_METHODS = new Set([ - "tools/call", - "prompts/get", - "resources/read" -]); -let writeClientIdentity; -let installDiscoverHandler; -let readServerIdentity; -/** -* Package-internal: backfills the connection-scoped client-identity fields of a -* per-request server instance from the request's validated `_meta` envelope, so the -* (deprecated) {@linkcode Server.getClientCapabilities} / {@linkcode Server.getClientVersion} -* accessors keep answering on instances that never see an `initialize` handshake. -* Not public API. -*/ -function mcp_DXXb3Vv3_seedClientIdentityFromEnvelope(server, identity) { - writeClientIdentity(server, identity); -} -/** -* Package-internal: installs the modern-only `server/discover` handler on an instance -* the HTTP entry has marked as serving the 2026-07-28 era, and makes sure the modern -* revisions the entry serves appear in the instance's supported-versions list (so the -* discover advertisement and version-mismatch errors name them). Idempotent. -* Hand-constructed instances are unaffected: nothing else calls this, so they keep -* answering `-32601` unless their own supported-versions list opts into a modern -* revision. Not public API. -*/ -function mcp_DXXb3Vv3_installModernOnlyHandlers(server, servedModernVersions) { - installDiscoverHandler(server, servedModernVersions); -} -/** -* Package-internal: the instance's implementation identity, for the serving -* entries to stamp onto entry-built results (the `subscriptions/listen` -* graceful-close result — built outside the encode seam, but the spec's -* `SubscriptionsListenResultMeta` extends `ResultMetaObject`, so it carries -* the serverInfo SHOULD like every other result). Not public API. -*/ -function mcp_DXXb3Vv3_serverIdentityOf(server) { - return readServerIdentity(server); -} -/** -* An MCP server on top of a pluggable transport. -* -* This server will automatically respond to the initialization flow as initiated from the client. -* -* @deprecated Use {@linkcode server/mcp.McpServer | McpServer} instead for the high-level API. Only use `Server` for advanced use cases. -*/ -var Server = class extends Protocol { - _clientCapabilities; - _clientVersion; - static { - writeClientIdentity = (server, identity) => { - if (identity.clientCapabilities !== void 0) server._clientCapabilities = identity.clientCapabilities; - if (identity.clientInfo !== void 0) server._clientVersion = identity.clientInfo; - }; - installDiscoverHandler = (server, servedModernVersions) => { - const missing = servedModernVersions.filter((version) => !server._supportedProtocolVersions.includes(version)); - if (missing.length > 0) server._supportedProtocolVersions = [...server._supportedProtocolVersions, ...missing]; - server.setRequestHandler("server/discover", () => server._ondiscover()); - }; - readServerIdentity = (server) => server._serverInfo; - } - _capabilities; - _instructions; - _jsonSchemaValidator; - _cacheHints; - _requestStateVerify; - _inputRequiredServing; - _legacyShim; - /** Lazily-built legacy shim; the loop lives in legacyInputRequiredShim.ts behind a narrow host contract. */ - _legacyInputRequiredShim() { - return this._legacyShim ??= new LegacyInputRequiredShim({ - maxRounds: this._inputRequiredServing.maxRounds, - roundTimeoutMs: this._inputRequiredServing.roundTimeoutMs, - resolvedClientCapabilities: (ctx) => this._inputRequestCapabilityView(ctx), - verifyRequestState: (state, ctx, method) => this._verifyRequestState(state, ctx, method), - sendElicitation: (params, options) => this._sendElicitationLeg(params, options, { validateAcceptedContent: false }), - sendSampling: (params, options) => this.createMessage(params, options), - listRoots: (params, options) => this.listRoots(params, options) - }); - } - /** - * Callback for when initialization has fully completed (i.e., the client has sent an `notifications/initialized` notification). - */ - oninitialized; - /** - * Initializes this server with the given name and version information. - */ - constructor(_serverInfo, options) { - super(options); - this._serverInfo = _serverInfo; - this._capabilities = options?.capabilities ? { ...options.capabilities } : {}; - this._instructions = options?.instructions; - this._jsonSchemaValidator = options?.jsonSchemaValidator ?? new AjvJsonSchemaValidator(); - this._requestStateVerify = options?.requestState?.verify; - this._inputRequiredServing = resolveLegacyShimOptions(options?.inputRequired); - if (options?.cacheHints !== void 0) { - for (const [operation, hint] of Object.entries(options.cacheHints)) if (hint !== void 0) assertValidCacheHint(hint, `cacheHints['${operation}']`); - this._cacheHints = options.cacheHints; - } - this.setRequestHandler("initialize", (request) => this._oninitialize(request)); - this.setNotificationHandler("notifications/initialized", () => this.oninitialized?.()); - if (modernProtocolVersions(this._supportedProtocolVersions).length > 0) this.setRequestHandler("server/discover", () => this._ondiscover()); - if (this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Registers the built-in `logging/setLevel` request handler. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - _registerLoggingHandler() { - this.setRequestHandler("logging/setLevel", async (request, ctx) => { - const transportSessionId = ctx.sessionId || ctx.http?.req?.headers.get("mcp-session-id") || void 0; - const { level } = request.params; - const parseResult = parseSchema(LoggingLevelSchema, level); - if (parseResult.success) this._loggingLevels.set(transportSessionId, parseResult.data); - return {}; - }); - } - buildContext(ctx, transportInfo) { - const hasHttpInfo = ctx.http || transportInfo?.request || transportInfo?.closeSSEStream || transportInfo?.closeStandaloneSSEStream; - return { - ...ctx, - mcpReq: { - ...ctx.mcpReq, - log: (level, data, logger) => { - if (!this._capabilities.logging) return Promise.resolve(); - let threshold; - if (this._servedModernEra()) { - threshold = ctx.mcpReq.envelope?.[LOG_LEVEL_META_KEY]; - if (threshold === void 0) return Promise.resolve(); - } else threshold = this._loggingLevels.get(ctx.sessionId) ?? this._loggingLevels.get(void 0); - if (threshold !== void 0 && this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(threshold)) return Promise.resolve(); - return ctx.mcpReq.notify({ - method: "notifications/message", - params: { - level, - data, - logger - } - }); - }, - elicitInput: (params, options) => this.elicitInput(params, options), - requestSampling: (params, options) => this.createMessage(params, options) - }, - http: hasHttpInfo ? { - ...ctx.http, - req: transportInfo?.request, - closeSSE: transportInfo?.closeSSEStream, - closeStandaloneSSE: transportInfo?.closeStandaloneSSEStream - } : void 0 - }; - } - _loggingLevels = /* @__PURE__ */ new Map(); - LOG_LEVEL_SEVERITY = new Map(LoggingLevelSchema.options.map((level, index) => [level, index])); - isMessageIgnored = (level, sessionId) => { - const currentLevel = this._loggingLevels.get(sessionId); - return currentLevel ? this.LOG_LEVEL_SEVERITY.get(level) < this.LOG_LEVEL_SEVERITY.get(currentLevel) : false; - }; - /** - * Registers new capabilities. This can only be called before connecting to a transport. - * - * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization). - */ - registerCapabilities(capabilities) { - if (this.transport) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.AlreadyConnected, "Cannot register capabilities after connecting to transport"); - const hadLogging = !!this._capabilities.logging; - this._capabilities = mergeCapabilities(this._capabilities, capabilities); - if (!hadLogging && this._capabilities.logging) this._registerLoggingHandler(); - } - /** - * Enforces server-side validation for `tools/call` results regardless of how the - * handler was registered, attaches the configured per-operation cache hint - * (when one exists) so the 2026-07-28 encode seam can fill `ttlMs`/`cacheScope` - * for results that do not provide their own, and owns the multi-round-trip - * seam: on the methods whose 2026-07-28 result vocabulary includes - * `input_required` (`tools/call`, `prompts/get`, `resources/read`) an - * input-required return skips result-schema validation and is checked - * against the served era, the at-least-one rule, and the request's own - * declared client capabilities; on every other method an input-required - * return is a server bug and fails loudly. The hint rides a symbol-keyed - * property that is never serialized, so 2025-era responses are unaffected. - */ - _wrapHandler(method, handler) { - if (method !== "tools/call") { - const cacheHint = this._cacheHints?.[method]; - const isInputRequiredCapable = INPUT_REQUIRED_CAPABLE_METHODS.has(method); - if (cacheHint === void 0 && !isInputRequiredCapable) return async (request, ctx) => { - const result = await handler(request, ctx); - if (isInputRequiredResult(result)) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - }; - return async (request, ctx) => { - const result = isInputRequiredCapable ? await this._invokeInputRequiredCapableHandler(method, handler, request, ctx) : await handler(request, ctx); - if (isInputRequiredResult(result)) { - if (!isInputRequiredCapable) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but only tools/call, prompts/get and resources/read support input_required (protocol revision 2026-07-28)`); - return result; - } - return cacheHint === void 0 ? result : attachCacheHintFallback(result, cacheHint); - }; - } - return async (request, ctx) => { - const codec = src_CX2iR2pK_codecForVersion(this._negotiatedProtocolVersion); - const validatedRequest = codec.validateRequest("tools/call", request); - if (!validatedRequest.ok) throw new src_CX2iR2pK_ProtocolError(validatedRequest.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validatedRequest.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call request: ${validatedRequest.message}`); - const result = await this._invokeInputRequiredCapableHandler("tools/call", handler, request, ctx); - if (isInputRequiredResult(result)) return result; - const normalizedResult = normalizeContentlessToolResult(result); - const validationResult = codec.validateResult("tools/call", normalizedResult); - if (!validationResult.ok) throw new src_CX2iR2pK_ProtocolError(validationResult.reason === "not-in-era" ? src_CX2iR2pK_ProtocolErrorCode.InternalError : src_CX2iR2pK_ProtocolErrorCode.InvalidParams, validationResult.reason === "not-in-era" ? "No wire schema for tools/call in the resolved era" : `Invalid tools/call result: ${validationResult.message}`); - return validationResult.value; - }; - } - /** - * Whether this instance is bound to a 2026-07-28-or-later protocol - * revision. Era is instance state — a serving entry (`createMcpHandler`, - * `serveStdio`) marks the instance modern at construction; a 2025-era - * `initialize` handshake binds it legacy. The multi-round-trip seam reads - * this directly: there is no per-request era consult. - */ - _servedModernEra() { - return this._negotiatedProtocolVersion !== void 0 && isModernProtocolVersion(this._negotiatedProtocolVersion); - } - /** - * Invokes a handler for one of the multi-round-trip methods and applies - * the input-required seam: - * - * - a `UrlElicitationRequiredError` (or any 2025-style server→client - * request idiom) escaping the handler on a request served on the - * 2026-07-28 era fails LOUDLY with a clear steer to - * `inputRequired.elicitUrl(...)` — the `-32042` error never reaches the - * 2026-07-28 wire and the throw is not silently converted. Requests - * served on the 2025 era keep today's `-32042` behavior byte-exact (the - * error is rethrown unchanged). - * - an input-required RETURN toward a 2026-07-28 request must satisfy - * the at-least-one rule, and every embedded request must be covered by - * the capabilities declared on the request's envelope (violations - * answer the typed `-32021` error). Toward a 2025-era request the - * return is fulfilled by the default-on legacy shim, whose own gate - * consults the initialize-declared capabilities and surfaces - * violations per family; `inputRequired.legacyShim: false` restores - * the pre-shim loud failure. - */ - async _invokeInputRequiredCapableHandler(method, handler, request, ctx) { - const servedModern = this._servedModernEra(); - const rawRequestState = ctx.mcpReq.requestState(); - if (rawRequestState !== void 0 && typeof rawRequestState !== "string") throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - let ctxForHandler = ctx; - if (typeof rawRequestState === "string") { - const decoded = await this._verifyRequestState(rawRequestState, ctx, method); - if (decoded !== void 0) ctxForHandler = withRequestStateValue(ctx, decoded); - } - let result; - try { - result = await handler(request, ctxForHandler); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) { - if (!servedModern) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `URL elicitation cannot be signalled by throwing UrlElicitationRequiredError on protocol revision ${this._negotiatedProtocolVersion}: return inputRequired({ inputRequests: { …: inputRequired.elicitUrl(...) } }) from the handler instead. The urlElicitationRequired error (-32042) of earlier revisions is not available on this revision.`); - } - throw error; - } - if (!isInputRequiredResult(result)) return result; - if (!servedModern) { - if (!this._inputRequiredServing.legacyShim) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result, but this request is served on protocol revision ${this._negotiatedProtocolVersion ?? LATEST_PROTOCOL_VERSION}, which has no input_required vocabulary`); - return await this._legacyInputRequiredShim().fulfill(method, handler, request, ctxForHandler, result); - } - const inputRequests = result.inputRequests; - const hasInputRequests = inputRequests != null && Object.keys(inputRequests).length > 0; - const hasRequestState = typeof result.requestState === "string"; - if (!hasInputRequests && !hasRequestState) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Handler for ${method} returned an input-required result with neither inputRequests nor requestState (every InputRequiredResult must include at least one of the two)`); - if (hasInputRequests) { - const declared = this._inputRequestCapabilityView(ctx); - for (const [key, entry] of Object.entries(inputRequests)) { - const { embedded, required } = coerceEmbeddedInputRequest(method, key, entry); - const missing = src_CX2iR2pK_missingClientCapabilities(required, declared); - if (missing !== void 0) throw new src_CX2iR2pK_MissingRequiredClientCapabilityError({ requiredCapabilities: missing }, `Cannot request input '${key}' (${embedded.method}): the request's client capabilities do not declare the required capability`); - } - } - return result; - } - /** - * Runs the configured `requestState.verify` hook and returns its - * resolved value (`undefined` when unconfigured or the hook returns - * nothing). Deny-on-error: any hook failure answers the frozen `-32602`; - * the reason goes to `onerror` only. - */ - async _verifyRequestState(state, ctx, method) { - if (this._requestStateVerify === void 0) return; - try { - return await this._requestStateVerify(state, ctx); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`requestState verification rejected ${method}: ${error instanceof Error ? error.message : String(error)}`)); - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "Invalid or expired requestState", { reason: "invalid_request_state" }); - } - } - /** - * The per-request resolved client-capabilities view: the request's own - * `_meta` envelope on the 2026 era; the `initialize`-declared state on a - * 2025-era connection. Per-request instances that never saw an - * initialize (stateless legacy) hold nothing, so gates refuse there. - */ - _inputRequestCapabilityView(ctx) { - return this._servedModernEra() ? ctx.mcpReq.envelope?.[auth_CUe6YdwF_CLIENT_CAPABILITIES_META_KEY] : this._clientCapabilities; - } - /** - * Guard for the push-style server→client request APIs ({@linkcode createMessage}, - * {@linkcode elicitInput}, {@linkcode listRoots}, {@linkcode ping}) on a - * modern-era instance: the 2026-07-28 revision has no server→client request - * channel, so the call fails before any wire traffic with a typed error - * whose message steers to `inputRequired(...)`. The base era gate would - * also reject it; this guard runs first to carry the steer. - */ - _assertPushApiInServedEra(method) { - if (this._servedModernEra()) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.MethodNotSupportedByProtocolVersion, `Server-to-client requests are not available on protocol revision ${this._negotiatedProtocolVersion}: '${method}' cannot be sent while serving a request on that revision. Return inputRequired({ ... }) from the handler instead — the client fulfils the embedded requests and retries the original request (multi round-trip requests).`, { - method, - era: "2026-07-28" - }); - } - assertCapabilityForMethod(method) { - switch (method) { - case "sampling/createMessage": - if (!this._clientCapabilities?.sampling) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support sampling (required for ${method})`); - break; - case "elicitation/create": - if (!this._clientCapabilities?.elicitation) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support elicitation (required for ${method})`); - break; - case "roots/list": - if (!this._clientCapabilities?.roots) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support listing roots (required for ${method})`); - break; - case "ping": break; - } - } - assertNotificationCapability(method) { - switch (method) { - case "notifications/message": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "notifications/resources/updated": - case "notifications/resources/list_changed": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying about resources (required for ${method})`); - break; - case "notifications/tools/list_changed": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of tool list changes (required for ${method})`); - break; - case "notifications/prompts/list_changed": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support notifying of prompt list changes (required for ${method})`); - break; - case "notifications/elicitation/complete": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Client does not support URL elicitation (required for ${method})`); - break; - case "notifications/cancelled": break; - case "notifications/progress": break; - } - } - assertRequestHandlerCapability(method) { - switch (method) { - case "completion/complete": - if (!this._capabilities.completions) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support completions (required for ${method})`); - break; - case "logging/setLevel": - if (!this._capabilities.logging) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support logging (required for ${method})`); - break; - case "prompts/get": - case "prompts/list": - if (!this._capabilities.prompts) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support prompts (required for ${method})`); - break; - case "resources/list": - case "resources/templates/list": - case "resources/read": - if (!this._capabilities.resources) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support resources (required for ${method})`); - break; - case "tools/call": - case "tools/list": - if (!this._capabilities.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, `Server does not support tools (required for ${method})`); - break; - case "ping": - case "initialize": break; - } - } - async _oninitialize(request) { - const requestedVersion = request.params.protocolVersion; - this._clientCapabilities = request.params.capabilities; - this._clientVersion = request.params.clientInfo; - const legacyVersions = legacyProtocolVersions(this._supportedProtocolVersions); - const protocolVersion = legacyVersions.includes(requestedVersion) ? requestedVersion : legacyVersions[0] ?? LATEST_PROTOCOL_VERSION; - this._negotiatedProtocolVersion = protocolVersion; - this.transport?.setProtocolVersion?.(protocolVersion); - return { - protocolVersion, - capabilities: this.getCapabilities(), - serverInfo: this._serverInfo, - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * Answers `server/discover` (protocol revision 2026-07-28). `supportedVersions` - * lists only modern revisions (2025-era versions are negotiated via `initialize`); - * the capabilities are advertised as-is, listChanged/subscribe bits included - * (see {@linkcode discoverAdvertisedCapabilities}). - */ - _ondiscover() { - return { - supportedVersions: modernProtocolVersions(this._supportedProtocolVersions), - capabilities: discoverAdvertisedCapabilities(this.getCapabilities()), - ...this._instructions && { instructions: this._instructions } - }; - } - /** - * The identity the 2026-era encode seam stamps into every outbound - * result's `_meta` under `io.modelcontextprotocol/serverInfo` (spec PR - * #3002: servers SHOULD identify themselves on every response). - */ - _outboundServerInfo() { - return this._serverInfo; - } - /** - * After initialization has completed, this will be populated with the client's reported capabilities. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * declared capabilities, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientCapabilities() { - return this._clientCapabilities; - } - /** - * After initialization has completed, this will be populated with information about the client's name and version. - * - * @deprecated Read client identity from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` carries the client's - * name and version, while on 2025-era connections this accessor keeps returning the - * `initialize`-scoped value. The accessor remains functional — instances serving the - * 2026-07-28 era are backfilled per request from the validated envelope. - */ - getClientVersion() { - return this._clientVersion; - } - /** - * After initialization has completed, this will be populated with the protocol version negotiated - * with the client (the version the server responded with during the initialize handshake), or - * `undefined` before initialization. - * - * @deprecated Read the protocol revision from the per-request handler context instead: on - * 2026-07-28 (per-request envelope) requests `ctx.mcpReq.envelope` names the revision the - * request was sent for, while on 2025-era connections this accessor keeps returning the - * `initialize`-negotiated version. The accessor remains functional — instances serving the - * 2026-07-28 era report that revision. - */ - getNegotiatedProtocolVersion() { - return this._negotiatedProtocolVersion; - } - /** - * Project a `tools/call` result through this instance's negotiated wire - * codec — the era-agnostic SEP-2106 §4.3 TextContent auto-append, plus on - * the 2025 era the `{result:…}` wrap when `structuredContent` is a - * non-object value or the advertised `outputSchema` had a non-object root. - * Identity for object-shaped `structuredContent` on the 2026 era. - * - * `McpServer`'s built-in `tools/call` handler routes through this method. - * Low-level `setRequestHandler('tools/call', …)` authors call it - * themselves so the projection lives in one place (the codec) and the - * server-side handler stays era-blind. - * - * This is the only codec function exposed on `Server` — the full - * `WireCodec` is intentionally not part of the public surface. - */ - projectCallToolResult(result, advertisedOutputSchema) { - return this._wireCodec().projectCallToolResult(result, advertisedOutputSchema); - } - /** - * Returns the current server capabilities. - */ - getCapabilities() { - return this._capabilities; - } - /** - * Sends a `ping` request to the connected client. - * - * @deprecated The 2026-07-28 protocol removed ping; it throws on a 2026-07-28-era instance. - * If your factory serves both eras, this only works on the legacy path. - */ - async ping() { - this._assertPushApiInServedEra("ping"); - return this.request({ method: "ping" }); - } - async createMessage(params, options) { - this._assertPushApiInServedEra("sampling/createMessage"); - if ((params.tools || params.toolChoice) && !this._clientCapabilities?.sampling?.tools) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support sampling tools capability."); - if (params.messages.length > 0) { - const lastMessage = params.messages.at(-1); - const lastContent = Array.isArray(lastMessage.content) ? lastMessage.content : [lastMessage.content]; - const hasToolResults = lastContent.some((c) => c.type === "tool_result"); - const previousMessage = params.messages.length > 1 ? params.messages.at(-2) : void 0; - const previousContent = previousMessage ? Array.isArray(previousMessage.content) ? previousMessage.content : [previousMessage.content] : []; - const hasPreviousToolUse = previousContent.some((c) => c.type === "tool_use"); - if (hasToolResults) { - if (lastContent.some((c) => c.type !== "tool_result")) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "The last message must contain only tool_result content if any is present"); - if (!hasPreviousToolUse) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "tool_result blocks are not matching any tool_use from the previous message"); - } - if (hasPreviousToolUse) { - const toolUseIds = new Set(previousContent.filter((c) => c.type === "tool_use").map((c) => c.id)); - const toolResultIds = new Set(lastContent.filter((c) => c.type === "tool_result").map((c) => c.toolUseId)); - if (toolUseIds.size !== toolResultIds.size || ![...toolUseIds].every((id) => toolResultIds.has(id))) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, "ids of tool_result blocks and tool_use blocks from previous message do not match"); - } - } - const hasTools = Boolean(params.tools || params.toolChoice); - const wide = await this.request({ - method: "sampling/createMessage", - params - }, options); - const outcome = this._wireCodec().samplingResultVariant(hasTools, wide); - if (!outcome.ok) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.InvalidResult, `Invalid sampling/createMessage result: ${outcome.reason === "invalid" ? outcome.message : outcome.reason}`); - return outcome.value; - } - /** - * Creates an elicitation request for the given parameters. - * For backwards compatibility, `mode` may be omitted for form requests and will default to `"form"`. - * @param params The parameters for the elicitation request. - * @param options Optional request options. - * @returns The result of the elicitation request. - * - * @deprecated Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) - * instead. The 2025 push-style server-to-client request model is replaced by input_required - * results in the 2026-07-28 protocol. If your factory serves both eras, this only works on the - * legacy path. - */ - async elicitInput(params, options) { - this._assertPushApiInServedEra("elicitation/create"); - switch (params.mode ?? "form") { - case "url": - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support url elicitation."); - break; - case "form": - if (!this._clientCapabilities?.elicitation?.form) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support form elicitation."); - break; - } - return this._sendElicitationLeg(params, options); - } - /** - * The capability-check-free core of {@linkcode elicitInput}. The shim - * uses it because its gate differs from the public checks: a bare - * `elicitation: {}` counts as form support (the pre-mode rule), and - * accepted content passes through unvalidated for parity with the - * modern client driver (handlers validate via the schema-aware - * `acceptedContent` overload and can re-ask). - */ - async _sendElicitationLeg(params, options, behavior) { - const mode = params.mode ?? "form"; - const validateAcceptedContent = behavior?.validateAcceptedContent ?? true; - switch (mode) { - case "url": { - const urlParams = params; - return this.request({ - method: "elicitation/create", - params: urlParams - }, options); - } - case "form": { - const formParams = params.mode === "form" ? params : { - ...params, - mode: "form" - }; - const result = await this.request({ - method: "elicitation/create", - params: formParams - }, options); - if (validateAcceptedContent && result.action === "accept" && result.content && formParams.requestedSchema) try { - const validationResult = this._jsonSchemaValidator.getValidator(formParams.requestedSchema)(result.content); - if (!validationResult.valid) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${validationResult.errorMessage}`); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError) throw error; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InternalError, `Error validating elicitation response: ${error instanceof Error ? error.message : String(error)}`); - } - return result; - } - } - } - /** - * Creates a reusable callback that, when invoked, will send a `notifications/elicitation/complete` - * notification for the specified elicitation ID. - * - * The notification (and the `elicitationId` it references) exists only on protocol revision - * 2025-11-25 — the 2026-07-28 revision removed both. On a connection negotiated at 2026-07-28 the - * returned callback rejects with a typed local error before anything reaches the transport - * (the method is not part of that revision's wire registry). - * - * @param elicitationId The ID of the elicitation to mark as complete. - * @param options Optional notification options. Useful when the completion notification should be related to a prior request. - * @returns A function that emits the completion notification when awaited. - */ - createElicitationCompletionNotifier(elicitationId, options) { - if (!this._clientCapabilities?.elicitation?.url) throw new src_CX2iR2pK_SdkError(src_CX2iR2pK_SdkErrorCode.CapabilityNotSupported, "Client does not support URL elicitation (required for notifications/elicitation/complete)"); - return () => this.notification({ - method: "notifications/elicitation/complete", - params: { elicitationId } - }, options); - } - /** - * Requests the list of roots from the client. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Throws on a 2026-07-28-era request — use {@link index.inputRequired | inputRequired} (multi-round-trip) instead, - * or migrate to passing paths via tool parameters, resource URIs, or configuration. The 2025 - * push-style server-to-client request model is replaced by input_required results in the - * 2026-07-28 protocol. If your factory serves both eras, this only works on the legacy path. - */ - async listRoots(params, options) { - this._assertPushApiInServedEra("roots/list"); - return this.request({ - method: "roots/list", - params - }, options); - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - if (this._capabilities.logging && !this.isMessageIgnored(params.level, sessionId)) return this.notification({ - method: "notifications/message", - params - }); - } - async sendResourceUpdated(params) { - return this.notification({ - method: "notifications/resources/updated", - params - }); - } - async sendResourceListChanged() { - return this.notification({ method: "notifications/resources/list_changed" }); - } - async sendToolListChanged() { - return this.notification({ method: "notifications/tools/list_changed" }); - } - async sendPromptListChanged() { - return this.notification({ method: "notifications/prompts/list_changed" }); - } -}; -/** -* The capability set a server advertises on `server/discover`. Pure — never -* mutates the input; the legacy `initialize` advertisement is untouched. -* -* The serving entries serve `subscriptions/listen` themselves, so the -* `listChanged` and `resources.subscribe` capability bits are advertised -* as-is: a modern-era client uses them to decide which notification types to -* request on its listen filter. -*/ -function discoverAdvertisedCapabilities(capabilities) { - return { ...capabilities }; -} - -//#endregion -//#region src/server/mcp.ts -/** -* High-level MCP server that provides a simpler API for working with resources, tools, and prompts. -* For advanced usage (like sending notifications or setting custom request handlers), use the underlying -* {@linkcode Server} instance available via the {@linkcode McpServer.server | server} property. -* -* @example -* ```ts source="./mcp.examples.ts#McpServer_basicUsage" -* const server = new McpServer({ -* name: 'my-server', -* version: '1.0.0' -* }); -* ``` -*/ -var mcp_DXXb3Vv3_McpServer = class { - /** - * The underlying {@linkcode Server} instance, useful for advanced operations like sending notifications. - */ - server; - _registeredResources = {}; - _registeredResourceTemplates = {}; - _registeredTools = {}; - _registeredPrompts = {}; - /** - * Per-tool JSON-converted `inputSchema`, memoized so the SEP-2243 - * registration-time scan and the pre-dispatch validation step share one - * conversion instead of paying it twice per request under the - * per-request-factory `createMcpHandler` model. - */ - _toolInputSchemaJson = {}; - /** - * The JSON-serialized `inputSchema` of a registered tool, or `undefined` - * when no such tool is registered. Used by the HTTP entry's pre-dispatch - * SEP-2243 `Mcp-Param-*` validation step (which needs the same JSON Schema - * `tools/list` would emit, before dispatch reaches the handler). - * - * @internal - */ - toolInputSchemaJson(name) { - const tool = this._registeredTools[name]; - if (tool === void 0 || !tool.enabled) return void 0; - if (Object.hasOwn(this._toolInputSchemaJson, name)) return this._toolInputSchemaJson[name]; - if (tool.inputSchema === void 0) return EMPTY_OBJECT_JSON_SCHEMA; - try { - const json = standardSchemaToJsonSchema(tool.inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - return json; - } catch { - return; - } - } - constructor(serverInfo, options) { - this.server = new Server(serverInfo, options); - if (options?.capabilities?.tools) this.setToolRequestHandlers(); - if (options?.capabilities?.resources) this.setResourceRequestHandlers(); - if (options?.capabilities?.prompts) this.setPromptRequestHandlers(); - } - /** - * Attaches to the given transport, starts it, and starts listening for messages. - * - * The `server` object assumes ownership of the {@linkcode Transport}, replacing any callbacks that have already been set, and expects that it is the only user of the {@linkcode Transport} instance going forward. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_connect_stdio" - * const server = new McpServer({ name: 'my-server', version: '1.0.0' }); - * const transport = new StdioServerTransport(); - * await server.connect(transport); - * ``` - */ - async connect(transport) { - return await this.server.connect(transport); - } - /** - * Closes the connection. - */ - async close() { - await this.server.close(); - } - _toolHandlersInitialized = false; - setToolRequestHandlers() { - if (this._toolHandlersInitialized) return; - this.server.assertCanSetRequestHandler("tools/list"); - this.server.assertCanSetRequestHandler("tools/call"); - this.server.registerCapabilities({ tools: { listChanged: this.server.getCapabilities().tools?.listChanged ?? true } }); - this.server.setRequestHandler("tools/list", () => ({ tools: Object.entries(this._registeredTools).filter(([, tool]) => tool.enabled).map(([name, tool]) => { - const toolDefinition = { - name, - title: tool.title, - description: tool.description, - inputSchema: tool.inputSchema ? standardSchemaToJsonSchema(tool.inputSchema, "input") : EMPTY_OBJECT_JSON_SCHEMA, - annotations: tool.annotations, - icons: tool.icons, - execution: tool.execution, - _meta: tool._meta - }; - if (tool.outputSchema) toolDefinition.outputSchema = standardSchemaToJsonSchema(tool.outputSchema, "output"); - return toolDefinition; - }) })); - this.server.setRequestHandler("tools/call", async (request, ctx) => { - const tool = this._registeredTools[request.params.name]; - if (!tool) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} not found`); - if (!tool.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Tool ${request.params.name} disabled`); - try { - const args = await this.validateToolInput(tool, request.params.arguments, request.params.name); - const result = await this.executeToolHandler(tool, args, ctx); - await this.validateToolOutput(tool, result, request.params.name); - if (isInputRequiredResult(result)) return result; - return this.server.projectCallToolResult(result, tool.outputSchemaJson); - } catch (error) { - if (error instanceof src_CX2iR2pK_ProtocolError && error.code === src_CX2iR2pK_ProtocolErrorCode.UrlElicitationRequired) throw error; - return this.createToolError(error instanceof Error ? error.message : String(error)); - } - }); - this._toolHandlersInitialized = true; - } - /** - * Creates a tool error result. - * - * @param errorMessage - The error message. - * @returns The tool error result. - */ - createToolError(errorMessage) { - return { - content: [{ - type: "text", - text: errorMessage - }], - isError: true - }; - } - /** - * Validates tool input arguments against the tool's input schema. - */ - async validateToolInput(tool, args, toolName) { - if (!tool.inputSchema) return; - const parseResult = await validateStandardSchema(tool.inputSchema, args ?? {}); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Input validation error: Invalid arguments for tool ${toolName}: ${parseResult.error}`); - return parseResult.data; - } - /** - * Validates tool output against the tool's output schema. - */ - async validateToolOutput(tool, result, toolName) { - if (!tool.outputSchema) return; - if (isInputRequiredResult(result)) return; - if (result.isError) return; - if (result.structuredContent === void 0) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Tool ${toolName} has an output schema but no structured content was provided`); - const parseResult = await validateStandardSchema(tool.outputSchema, result.structuredContent); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Output validation error: Invalid structured content for tool ${toolName}: ${parseResult.error}`); - } - /** - * Executes a tool handler. - */ - async executeToolHandler(tool, args, ctx) { - return tool.executor(args, ctx); - } - _completionHandlerInitialized = false; - setCompletionRequestHandler() { - if (this._completionHandlerInitialized) return; - this.server.assertCanSetRequestHandler("completion/complete"); - this.server.registerCapabilities({ completions: {} }); - this.server.setRequestHandler("completion/complete", async (request) => { - switch (request.params.ref.type) { - case "ref/prompt": - assertCompleteRequestPrompt(request); - return this.handlePromptCompletion(request, request.params.ref); - case "ref/resource": - assertCompleteRequestResourceTemplate(request); - return this.handleResourceCompletion(request, request.params.ref); - default: throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`); - } - }); - this._completionHandlerInitialized = true; - } - async handlePromptCompletion(request, ref) { - const prompt = this._registeredPrompts[ref.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${ref.name} disabled`); - if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT; - const field = unwrapOptionalSchema(getSchemaShape(prompt.argsSchema)?.[request.params.argument.name]); - if (!isCompletable(field)) return EMPTY_COMPLETION_RESULT; - const completer = getCompleter(field); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - async handleResourceCompletion(request, ref) { - const template = Object.values(this._registeredResourceTemplates).find((t) => t.resourceTemplate.uriTemplate.toString() === ref.uri); - if (!template) { - if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT; - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`); - } - const completer = template.resourceTemplate.completeCallback(request.params.argument.name); - if (!completer) return EMPTY_COMPLETION_RESULT; - return createCompletionResult(await completer(request.params.argument.value, request.params.context)); - } - _resourceHandlersInitialized = false; - setResourceRequestHandlers() { - if (this._resourceHandlersInitialized) return; - this.server.assertCanSetRequestHandler("resources/list"); - this.server.assertCanSetRequestHandler("resources/templates/list"); - this.server.assertCanSetRequestHandler("resources/read"); - this.server.registerCapabilities({ resources: { listChanged: this.server.getCapabilities().resources?.listChanged ?? true } }); - this.server.setRequestHandler("resources/list", async (_request, ctx) => { - const resources = Object.entries(this._registeredResources).filter(([_, resource]) => resource.enabled).map(([uri, resource]) => ({ - uri, - name: resource.name, - ...resource.metadata - })); - const templateResources = []; - for (const template of Object.values(this._registeredResourceTemplates)) { - if (!template.resourceTemplate.listCallback) continue; - const result = await template.resourceTemplate.listCallback(ctx); - for (const resource of result.resources) templateResources.push({ - ...template.metadata, - ...resource - }); - } - return { resources: [...resources, ...templateResources] }; - }); - this.server.setRequestHandler("resources/templates/list", async () => { - return { resourceTemplates: Object.entries(this._registeredResourceTemplates).map(([name, template]) => ({ - name, - uriTemplate: template.resourceTemplate.uriTemplate.toString(), - ...template.metadata - })) }; - }); - this.server.setRequestHandler("resources/read", async (request, ctx) => { - let uri; - try { - uri = new URL(request.params.uri); - } catch { - throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource URI ${request.params.uri} is invalid`, { - uri: request.params.uri, - reason: "invalid_uri" - }); - } - const resource = this._registeredResources[uri.toString()]; - if (resource) { - if (!resource.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Resource ${uri} disabled`); - return attachCacheHintFallback(await resource.readCallback(uri, ctx), resource.cacheHint); - } - for (const template of Object.values(this._registeredResourceTemplates)) { - const variables = template.resourceTemplate.uriTemplate.match(uri.toString()); - if (variables) return attachCacheHintFallback(await template.readCallback(uri, variables, ctx), template.cacheHint); - } - throw new ResourceNotFoundError(request.params.uri); - }); - this._resourceHandlersInitialized = true; - } - _promptHandlersInitialized = false; - setPromptRequestHandlers() { - if (this._promptHandlersInitialized) return; - this.server.assertCanSetRequestHandler("prompts/list"); - this.server.assertCanSetRequestHandler("prompts/get"); - this.server.registerCapabilities({ prompts: { listChanged: this.server.getCapabilities().prompts?.listChanged ?? true } }); - this.server.setRequestHandler("prompts/list", () => ({ prompts: Object.entries(this._registeredPrompts).filter(([, prompt]) => prompt.enabled).map(([name, prompt]) => { - return { - name, - title: prompt.title, - description: prompt.description, - arguments: prompt.argsSchema ? promptArgumentsFromStandardSchema(prompt.argsSchema) : void 0, - icons: prompt.icons, - _meta: prompt._meta - }; - }) })); - this.server.setRequestHandler("prompts/get", async (request, ctx) => { - const prompt = this._registeredPrompts[request.params.name]; - if (!prompt) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} not found`); - if (!prompt.enabled) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`); - return prompt.handler(request.params.arguments, ctx); - }); - this._promptHandlersInitialized = true; - } - registerResource(name, uriOrTemplate, config, readCallback) { - const cacheHint = config.cacheHint; - let metadata = config; - if (cacheHint !== void 0) { - assertValidCacheHint(cacheHint, `resource ${name}`); - const rest = { ...config }; - delete rest.cacheHint; - metadata = rest; - } - if (typeof uriOrTemplate === "string") { - if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`); - const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResource.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResource; - } else { - if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`); - const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, metadata, readCallback); - if (cacheHint !== void 0) registeredResourceTemplate.cacheHint = cacheHint; - this.setResourceRequestHandlers(); - this.sendResourceListChanged(); - return registeredResourceTemplate; - } - } - _createRegisteredResource(name, title, uri, metadata, readCallback) { - const registeredResource = { - name, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResource.update({ enabled: false }), - enable: () => registeredResource.update({ enabled: true }), - remove: () => registeredResource.update({ uri: null }), - update: (updates) => { - if (updates.uri !== void 0 && updates.uri !== uri) { - delete this._registeredResources[uri]; - if (updates.uri) this._registeredResources[updates.uri] = registeredResource; - } - if (updates.name !== void 0) registeredResource.name = updates.name; - if (updates.title !== void 0) registeredResource.title = updates.title; - if (updates.metadata !== void 0) registeredResource.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResource.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResource.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResources[uri] = registeredResource; - return registeredResource; - } - _createRegisteredResourceTemplate(name, title, template, metadata, readCallback) { - const registeredResourceTemplate = { - resourceTemplate: template, - title, - metadata, - readCallback, - enabled: true, - disable: () => registeredResourceTemplate.update({ enabled: false }), - enable: () => registeredResourceTemplate.update({ enabled: true }), - remove: () => registeredResourceTemplate.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredResourceTemplates[name]; - if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate; - } - if (updates.title !== void 0) registeredResourceTemplate.title = updates.title; - if (updates.template !== void 0) registeredResourceTemplate.resourceTemplate = updates.template; - if (updates.metadata !== void 0) registeredResourceTemplate.metadata = updates.metadata; - if (updates.callback !== void 0) registeredResourceTemplate.readCallback = updates.callback; - if (updates.enabled !== void 0) registeredResourceTemplate.enabled = updates.enabled; - this.sendResourceListChanged(); - } - }; - this._registeredResourceTemplates[name] = registeredResourceTemplate; - const variableNames = template.uriTemplate.variableNames; - if (Array.isArray(variableNames) && variableNames.some((v) => !!template.completeCallback(v))) this.setCompletionRequestHandler(); - return registeredResourceTemplate; - } - _createRegisteredPrompt(name, title, description, argsSchema, callback, icons, _meta) { - let currentArgsSchema = argsSchema; - let currentCallback = callback; - const registeredPrompt = { - title, - description, - argsSchema, - icons, - _meta, - handler: createPromptHandler(name, argsSchema, callback), - enabled: true, - disable: () => registeredPrompt.update({ enabled: false }), - enable: () => registeredPrompt.update({ enabled: true }), - remove: () => registeredPrompt.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - delete this._registeredPrompts[name]; - if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt; - } - if (updates.title !== void 0) registeredPrompt.title = updates.title; - if (updates.description !== void 0) registeredPrompt.description = updates.description; - if (updates.icons !== void 0) registeredPrompt.icons = updates.icons; - if (updates._meta !== void 0) registeredPrompt._meta = updates._meta; - let needsHandlerRegen = false; - if (updates.argsSchema !== void 0) { - registeredPrompt.argsSchema = updates.argsSchema; - currentArgsSchema = updates.argsSchema; - needsHandlerRegen = true; - } - if (updates.callback !== void 0) { - currentCallback = updates.callback; - needsHandlerRegen = true; - } - if (needsHandlerRegen) registeredPrompt.handler = createPromptHandler(name, currentArgsSchema, currentCallback); - if (updates.enabled !== void 0) registeredPrompt.enabled = updates.enabled; - this.sendPromptListChanged(); - } - }; - this._registeredPrompts[name] = registeredPrompt; - if (argsSchema) { - const shape = getSchemaShape(argsSchema); - if (shape) { - if (Object.values(shape).some((field) => { - return isCompletable(unwrapOptionalSchema(field)); - })) this.setCompletionRequestHandler(); - } - } - return registeredPrompt; - } - _createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, icons, execution, _meta, handler) { - validateAndWarnToolName(name); - if (inputSchema !== void 0) try { - const json = standardSchemaToJsonSchema(inputSchema, "input"); - this._toolInputSchemaJson[name] = json; - const scan = src_CX2iR2pK_scanXMcpHeaderDeclarations(json); - if (!scan.valid) console.warn(`[mcp-sdk] tool '${name}' carries an invalid x-mcp-header declaration and will be excluded by conforming Streamable HTTP clients: ${scan.reason}`); - } catch {} - let currentHandler = handler; - const registeredTool = { - title, - description, - inputSchema, - outputSchema, - outputSchemaJson: convertOutputSchemaJson(outputSchema), - annotations, - icons, - execution, - _meta, - handler, - executor: createToolExecutor(inputSchema, handler), - enabled: true, - disable: () => registeredTool.update({ enabled: false }), - enable: () => registeredTool.update({ enabled: true }), - remove: () => registeredTool.update({ name: null }), - update: (updates) => { - if (updates.name !== void 0 && updates.name !== name) { - if (typeof updates.name === "string") validateAndWarnToolName(updates.name); - delete this._registeredTools[name]; - delete this._toolInputSchemaJson[name]; - if (updates.name) { - delete this._toolInputSchemaJson[updates.name]; - this._registeredTools[updates.name] = registeredTool; - name = updates.name; - } - } - if (updates.title !== void 0) registeredTool.title = updates.title; - if (updates.description !== void 0) registeredTool.description = updates.description; - let needsExecutorRegen = false; - if (updates.paramsSchema !== void 0) { - registeredTool.inputSchema = updates.paramsSchema; - delete this._toolInputSchemaJson[name]; - needsExecutorRegen = true; - } - if (updates.callback !== void 0) { - registeredTool.handler = updates.callback; - currentHandler = updates.callback; - needsExecutorRegen = true; - } - if (needsExecutorRegen) registeredTool.executor = createToolExecutor(registeredTool.inputSchema, currentHandler); - if (updates.outputSchema !== void 0) { - registeredTool.outputSchema = updates.outputSchema; - registeredTool.outputSchemaJson = convertOutputSchemaJson(updates.outputSchema); - } - if (updates.annotations !== void 0) registeredTool.annotations = updates.annotations; - if (updates.icons !== void 0) registeredTool.icons = updates.icons; - if (updates._meta !== void 0) registeredTool._meta = updates._meta; - if (updates.enabled !== void 0) registeredTool.enabled = updates.enabled; - this.sendToolListChanged(); - } - }; - this._registeredTools[name] = registeredTool; - this.setToolRequestHandlers(); - this.sendToolListChanged(); - return registeredTool; - } - registerTool(name, config, cb) { - if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`); - const { title, description, inputSchema, outputSchema, annotations, icons, _meta } = config; - return this._createRegisteredTool(name, title, description, normalizeRawShapeSchema(inputSchema), normalizeRawShapeSchema(outputSchema), annotations, icons, void 0, _meta, cb); - } - registerPrompt(name, config, cb) { - if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`); - const { title, description, argsSchema, icons, _meta } = config; - const registeredPrompt = this._createRegisteredPrompt(name, title, description, normalizeRawShapeSchema(argsSchema), cb, icons, _meta); - this.setPromptRequestHandlers(); - this.sendPromptListChanged(); - return registeredPrompt; - } - /** - * Checks if the server is connected to a transport. - * @returns `true` if the server is connected - */ - isConnected() { - return this.server.transport !== void 0; - } - /** - * Sends a logging message to the client, if connected. - * Note: You only need to send the parameters object, not the entire JSON-RPC message. - * @see {@linkcode LoggingMessageNotification} - * @param params - * @param sessionId Optional for stateless transports and backward compatibility. - * - * @example - * ```ts source="./mcp.examples.ts#McpServer_sendLoggingMessage_basic" - * await server.sendLoggingMessage({ - * level: 'info', - * data: 'Processing complete' - * }); - * ``` - * - * @deprecated Deprecated as of protocol version 2026-07-28 (SEP-2577). - * Remains functional during the deprecation window (at least twelve months). - * Migrate to stderr logging (STDIO servers) or OpenTelemetry. - */ - async sendLoggingMessage(params, sessionId) { - return this.server.sendLoggingMessage(params, sessionId); - } - /** - * Sends a resource list changed event to the client, if connected. - */ - sendResourceListChanged() { - if (this.isConnected()) this.server.sendResourceListChanged(); - } - /** - * Sends a tool list changed event to the client, if connected. - */ - sendToolListChanged() { - if (this.isConnected()) this.server.sendToolListChanged(); - } - /** - * Sends a prompt list changed event to the client, if connected. - */ - sendPromptListChanged() { - if (this.isConnected()) this.server.sendPromptListChanged(); - } -}; -/** -* A resource template combines a URI pattern with optional functionality to enumerate -* all resources matching that pattern. -*/ -var ResourceTemplate = class { - _uriTemplate; - constructor(uriTemplate, _callbacks) { - this._callbacks = _callbacks; - this._uriTemplate = typeof uriTemplate === "string" ? new UriTemplate(uriTemplate) : uriTemplate; - } - /** - * Gets the URI template pattern. - */ - get uriTemplate() { - return this._uriTemplate; - } - /** - * Gets the list callback, if one was provided. - */ - get listCallback() { - return this._callbacks.list; - } - /** - * Gets the callback for completing a specific URI template variable, if one was provided. - */ - completeCallback(variable) { - return this._callbacks.complete?.[variable]; - } -}; -/** -* Creates an executor that invokes the handler with the appropriate arguments. -* When `inputSchema` is defined, the handler is called with `(args, ctx)`. -* When `inputSchema` is undefined, the handler is called with just `(ctx)`. -*/ -function createToolExecutor(inputSchema, handler) { - if (inputSchema) { - const callback$1 = handler; - return async (args, ctx) => callback$1(args, ctx); - } - const callback = handler; - return async (_args, ctx) => callback(ctx); -} -const EMPTY_OBJECT_JSON_SCHEMA = { - type: "object", - properties: {} -}; -/** -* Convert a registered `outputSchema` to JSON Schema, memoised on {@link RegisteredTool.outputSchemaJson} -* so `tools/call` passes the SAME advertised schema to the wire codec's `projectCallToolResult` that -* `tools/list` emits (and that the 2025 codec's `encodeResult('tools/list', …)` may wrap). A conversion -* failure yields `undefined` so the failure surfaces where it always has (`tools/list`). -*/ -function convertOutputSchemaJson(outputSchema) { - if (outputSchema === void 0) return void 0; - try { - return standardSchemaToJsonSchema(outputSchema, "output"); - } catch { - return; - } -} -/** -* Creates a type-safe prompt handler that captures the schema and callback in a closure. -* This eliminates the need for type assertions at the call site. -*/ -function createPromptHandler(name, argsSchema, callback) { - if (argsSchema) { - const typedCallback = callback; - return async (args, ctx) => { - const parseResult = await validateStandardSchema(argsSchema, args); - if (!parseResult.success) throw new src_CX2iR2pK_ProtocolError(src_CX2iR2pK_ProtocolErrorCode.InvalidParams, `Invalid arguments for prompt ${name}: ${parseResult.error}`); - return typedCallback(parseResult.data, ctx); - }; - } else { - const typedCallback = callback; - return async (_args, ctx) => { - return typedCallback(ctx); - }; - } -} -function createCompletionResult(suggestions) { - return { completion: { - values: suggestions.map(String).slice(0, 100), - total: suggestions.length, - hasMore: suggestions.length > 100 - } }; -} -const EMPTY_COMPLETION_RESULT = { completion: { - values: [], - hasMore: false -} }; -/** @internal Gets the shape of a Zod object schema */ -function getSchemaShape(schema) { - const candidate = schema; - if (candidate.shape && typeof candidate.shape === "object") return candidate.shape; -} -/** @internal Checks if a Zod schema is optional */ -function isOptionalSchema(schema) { - return schema?.type === "optional"; -} -/** @internal Unwraps an optional Zod schema */ -function unwrapOptionalSchema(schema) { - if (!isOptionalSchema(schema)) return schema; - return schema.def?.innerType ?? schema; -} - -//#endregion - -//# sourceMappingURL=mcp-DXXb3Vv3.mjs.map - - - - -//#region src/server/perRequestTransport.ts -/** -* The per-request micro-transport: a real, connected `Transport` whose whole -* lifetime is one HTTP exchange. See the module documentation for the -* response shapes it produces. -*/ -var PerRequestHTTPServerTransport = class { - onclose; - onerror; - onmessage; - _classification; - _responseMode; - _started = false; - _used = false; - _closed = false; - _terminalDelivered = false; - /** - * `true` only while the inbound message is being delivered synchronously - * to the connected protocol layer. The pre-handler gates (the era - * registry gate, the edge→instance handoff check, the missing-handler - * rejection) answer inside this window; request handlers always run - * after it (the protocol layer defers them to a microtask). An error - * sent inside the window is therefore ladder-originated, and an error - * sent after it is handler-produced. - */ - _dispatchWindowOpen = false; - _requestId; - _deferredResponse; - _sse; - _abortCleanup; - _keepAliveMs; - constructor(options) { - this._classification = options.classification; - this._responseMode = options.responseMode ?? "auto"; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - async start() { - if (this._started) throw new Error("PerRequestHTTPServerTransport is already started"); - this._started = true; - } - /** - * Serves the single exchange: delivers the classified message to the - * connected server instance and resolves with the HTTP response. - * - * Throws when called a second time (the transport is strictly - * single-use), or before a server has been connected to the transport. - * The returned promise rejects with a connection-closed error when the - * transport is closed before a response was produced (for example because - * the client disconnected). - */ - async handleMessage(message, extra) { - if (this._used) throw new Error("PerRequestHTTPServerTransport serves exactly one exchange; construct a new transport per request"); - if (!this._started || this.onmessage === void 0) throw new Error("PerRequestHTTPServerTransport is not connected: connect a server to this transport before handling a message"); - if (this._closed) throw new Error("PerRequestHTTPServerTransport is closed"); - this._used = true; - const signal = extra?.request?.signal; - if (signal?.aborted) { - await this.close(); - throw new SdkError(SdkErrorCode.ConnectionClosed, "The request was aborted before it could be handled"); - } - const messageExtra = { - classification: this._classification, - ...extra?.request !== void 0 && { request: extra.request }, - ...extra?.authInfo !== void 0 && { authInfo: extra.authInfo } - }; - if (isJSONRPCRequest(message)) { - this._requestId = message.id; - let resolve; - let reject; - const promise = new Promise((promiseResolve, promiseReject) => { - resolve = promiseResolve; - reject = promiseReject; - }); - this._deferredResponse = { - promise, - resolve, - reject, - settled: false - }; - if (signal !== void 0) { - const onAbort = () => void this.close(); - signal.addEventListener("abort", onAbort, { once: true }); - this._abortCleanup = () => signal.removeEventListener("abort", onAbort); - } - this._dispatchWindowOpen = true; - try { - this.onmessage(message, messageExtra); - } finally { - this._dispatchWindowOpen = false; - } - if (this._responseMode === "sse" && !this._closed && !this._deferredResponse.settled) this.upgradeToSse(); - return promise; - } - this.onmessage(message, messageExtra); - return new Response(null, { status: 202 }); - } - async send(message, options) { - if (this._closed) return; - const isResponse = isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message); - const relatedId = isResponse ? message.id : options?.relatedRequestId; - if (this._requestId === void 0 || relatedId === void 0 || relatedId !== this._requestId) { - if (isResponse) this.onerror?.(/* @__PURE__ */ new Error(`Received a response for an unknown request id: ${String(message.id)}`)); - return; - } - if (isResponse) { - if (this._terminalDelivered) return; - this._terminalDelivered = true; - const errorCode = isJSONRPCErrorResponse(message) ? message.error.code : void 0; - const ladderStatus = errorCode !== void 0 && (this._dispatchWindowOpen || errorCode === ProtocolErrorCode.MissingRequiredClientCapability) ? LADDER_ERROR_HTTP_STATUS[errorCode] : void 0; - if (ladderStatus !== void 0 && this._sse === void 0) { - this.settleResponse(Response.json(message, { - status: ladderStatus, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._sse !== void 0 || this._responseMode === "sse") { - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - this.finalizeStream(); - return; - } - this.settleResponse(Response.json(message, { - status: 200, - headers: { "Content-Type": "application/json" } - })); - queueMicrotask(() => void this.close()); - return; - } - if (this._responseMode === "json") return; - if (this._sse === void 0) this.upgradeToSse(); - this.writeMessageFrame(message); - } - /** - * Writes an SSE comment frame (a keep-alive heartbeat). Dropped when the - * exchange is not currently streaming. - */ - writeCommentFrame(comment) { - if (this._closed || this._sse === void 0 || this._sse.closed) return; - const frame = comment.split("\n").map((line) => `: ${line}`).join("\n"); - this.writeFrame(`${frame}\n\n`); - } - async close() { - if (this._closed) return; - this._closed = true; - this._abortCleanup?.(); - this._abortCleanup = void 0; - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - if (this._deferredResponse !== void 0 && !this._deferredResponse.settled) { - this._deferredResponse.settled = true; - this._deferredResponse.reject(new SdkError(SdkErrorCode.ConnectionClosed, "Connection closed before a response was produced")); - } - this.onclose?.(); - } - settleResponse(response) { - if (this._deferredResponse === void 0 || this._deferredResponse.settled) return; - this._deferredResponse.settled = true; - this._deferredResponse.resolve(response); - } - upgradeToSse() { - let controller; - const readable = new ReadableStream({ - start: (streamController) => { - controller = streamController; - }, - cancel: () => { - this.close(); - } - }); - this._sse = { - controller, - encoder: new TextEncoder(), - closed: false - }; - this._sse.keepAliveTimer = armSseKeepAlive(this._keepAliveMs, () => this.writeCommentFrame("keepalive")); - this.settleResponse(new Response(readable, { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - } - })); - } - finalizeStream() { - if (this._sse?.keepAliveTimer !== void 0) clearInterval(this._sse.keepAliveTimer); - if (this._sse !== void 0 && !this._sse.closed) { - this._sse.closed = true; - try { - this._sse.controller.close(); - } catch {} - } - queueMicrotask(() => void this.close()); - } - writeMessageFrame(message) { - this.writeFrame(`event: message\ndata: ${JSON.stringify(message)}\n\n`); - } - writeFrame(frame) { - if (this._sse === void 0 || this._sse.closed) return; - try { - this._sse.controller.enqueue(this._sse.encoder.encode(frame)); - } catch (error) { - this.onerror?.(/* @__PURE__ */ new Error(`Failed to write to the response stream: ${error}`)); - } - } -}; - -//#endregion -//#region src/server/invoke.ts -/** -* Serves one classified inbound message on the given server instance and -* returns the HTTP response for the exchange. -* -* The instance is connected to a fresh single-exchange transport, the message -* is injected through the normal transport message path, and whatever the -* dispatch layer produces (the handler result, a protocol-level rejection, or -* streamed related messages followed by the result) is captured as the -* returned `Response`. For request exchanges, teardown rides the transport's -* close chain once the terminal response has been delivered; notification -* exchanges resolve with the 202 response immediately and do NOT run the -* close chain — the transport stays connected until the caller closes it or -* drops the per-request instance, which is the caller's choice either way. -*/ -async function invoke(server, message, ctx) { - const transport = new PerRequestHTTPServerTransport({ - classification: ctx.classification, - ...ctx.responseMode !== void 0 && { responseMode: ctx.responseMode }, - ...ctx.keepAliveMs !== void 0 && { keepAliveMs: ctx.keepAliveMs } - }); - await server.connect(transport); - return transport.handleMessage(message, { - ...ctx.request !== void 0 && { request: ctx.request }, - ...ctx.authInfo !== void 0 && { authInfo: ctx.authInfo } - }); -} - -//#endregion -//#region src/server/streamableHttp.ts -/** -* Server transport for Web Standards Streamable HTTP: this implements the MCP Streamable HTTP transport specification -* using Web Standard APIs (`Request`, `Response`, `ReadableStream`). -* -* This transport works on any runtime that supports Web Standards: Node.js 18+, Cloudflare Workers, Deno, Bun, etc. -* -* In stateful mode: -* - Session ID is generated and included in response headers -* - Session ID is always included in initialization responses -* - Requests with invalid session IDs are rejected with `404 Not Found` -* - Non-initialization requests without a session ID are rejected with `400 Bad Request` -* - State is maintained in-memory (connections, message history) -* -* In stateless mode: -* - No Session ID is included in any responses -* - No session validation is performed -* -* @example Stateful setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateful" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: () => crypto.randomUUID() -* }); -* -* await server.connect(transport); -* ``` -* -* @example Stateless setup -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_stateless" -* const transport = new WebStandardStreamableHTTPServerTransport({ -* sessionIdGenerator: undefined -* }); -* ``` -* -* @example Hono.js -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_hono" -* app.all('/mcp', async c => { -* return transport.handleRequest(c.req.raw); -* }); -* ``` -* -* @example Cloudflare Workers -* ```ts source="./streamableHttp.examples.ts#WebStandardStreamableHTTPServerTransport_workers" -* const worker = { -* async fetch(request: Request): Promise { -* return transport.handleRequest(request); -* } -* }; -* ``` -*/ -var WebStandardStreamableHTTPServerTransport = class { - sessionIdGenerator; - _started = false; - _closed = false; - _streamMapping = /* @__PURE__ */ new Map(); - _requestToStreamMapping = /* @__PURE__ */ new Map(); - _requestResponseMap = /* @__PURE__ */ new Map(); - _initialized = false; - _enableJsonResponse = false; - _standaloneSseStreamId = "_GET_stream"; - _eventStore; - _onsessioninitialized; - _onsessionclosed; - _allowedHosts; - _allowedOrigins; - _enableDnsRebindingProtection; - _retryInterval; - _supportedProtocolVersions; - _keepAliveMs; - sessionId; - onclose; - onerror; - onmessage; - constructor(options = {}) { - this.sessionIdGenerator = options.sessionIdGenerator; - this._enableJsonResponse = options.enableJsonResponse ?? false; - this._eventStore = options.eventStore; - this._onsessioninitialized = options.onsessioninitialized; - this._onsessionclosed = options.onsessionclosed; - this._allowedHosts = options.allowedHosts; - this._allowedOrigins = options.allowedOrigins; - this._enableDnsRebindingProtection = options.enableDnsRebindingProtection ?? false; - this._retryInterval = options.retryInterval; - this._supportedProtocolVersions = options.supportedProtocolVersions ?? SUPPORTED_PROTOCOL_VERSIONS; - this._keepAliveMs = options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS; - } - startKeepAlive(controller, encoder) { - if (this._closed) return void 0; - const timer = armSseKeepAlive(this._keepAliveMs, () => { - try { - controller.enqueue(encoder.encode(": keepalive\n\n")); - } catch { - if (timer !== void 0) clearInterval(timer); - } - }); - return timer; - } - /** - * Starts the transport. This is required by the {@linkcode Transport} interface but is a no-op - * for the Streamable HTTP transport as connections are managed per-request. - */ - async start() { - if (this._started) throw new Error("Transport already started"); - this._started = true; - } - /** - * Sets the supported protocol versions for header validation. - * Called by the server during {@linkcode server/server.Server.connect | connect()} to pass its supported versions. - */ - setSupportedProtocolVersions(versions) { - this._supportedProtocolVersions = versions; - } - /** - * Helper to create a JSON error response - */ - createJsonErrorResponse(status, code, message, options) { - const error = { - code, - message - }; - if (options?.data !== void 0) error.data = options.data; - return Response.json({ - jsonrpc: "2.0", - error, - id: null - }, { - status, - headers: { - "Content-Type": "application/json", - ...options?.headers - } - }); - } - /** - * Validates request headers for DNS rebinding protection. - * @returns Error response if validation fails, `undefined` if validation passes. - */ - validateRequestHeaders(req) { - if (!this._enableDnsRebindingProtection) return; - if (this._allowedHosts && this._allowedHosts.length > 0) { - const hostHeader = req.headers.get("host"); - if (!hostHeader || !this._allowedHosts.includes(hostHeader)) { - const error = `Invalid Host header: ${hostHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - if (this._allowedOrigins && this._allowedOrigins.length > 0) { - const originHeader = req.headers.get("origin"); - if (originHeader && !this._allowedOrigins.includes(originHeader)) { - const error = `Invalid Origin header: ${originHeader}`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(403, -32e3, error); - } - } - } - /** - * Handles an incoming HTTP request, whether `GET`, `POST`, or `DELETE` - * Returns a `Response` object (Web Standard) - */ - async handleRequest(req, options) { - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const validationError = this.validateRequestHeaders(req); - if (validationError) return validationError; - switch (req.method) { - case "POST": return this.handlePostRequest(req, options); - case "GET": return this.handleGetRequest(req); - case "DELETE": return this.handleDeleteRequest(req); - default: return this.handleUnsupportedRequest(); - } - } - /** - * Returns true if the client's protocol version supports empty SSE data in - * priming events (the fix shipped with protocol version `2025-11-25`). - * - * The version is checked for membership in this transport instance's - * supported protocol versions rather than with an open-ended - * `>= '2025-11-25'` comparison: the value may come from an `initialize` - * request body, which (unlike the `MCP-Protocol-Version` header) is not - * validated against `supportedProtocolVersions` before reaching this - * check. An unknown future version string must not silently enable - * behavior reserved for versions this transport actually supports. - */ - supportsEmptySSEData(protocolVersion) { - return this._supportedProtocolVersions.includes(protocolVersion) && protocolVersion >= "2025-11-25"; - } - /** - * Writes a priming event to establish resumption capability. - * Only sends if `eventStore` is configured (opt-in for resumability) and - * the client's protocol version supports empty SSE data (a supported - * version that is >= `2025-11-25`). - */ - async writePrimingEvent(controller, encoder, streamId, protocolVersion) { - if (!this._eventStore) return; - if (!this.supportsEmptySSEData(protocolVersion)) return; - const primingEventId = await this._eventStore.storeEvent(streamId, {}); - let primingEvent = `id: ${primingEventId}\ndata: \n\n`; - if (this._retryInterval !== void 0) primingEvent = `id: ${primingEventId}\nretry: ${this._retryInterval}\ndata: \n\n`; - controller.enqueue(encoder.encode(primingEvent)); - } - /** - * Handles `GET` requests for SSE stream - */ - async handleGetRequest(req) { - if (!req.headers.get("accept")?.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept text/event-stream"); - } - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - if (this._eventStore) { - const lastEventId = req.headers.get("last-event-id"); - if (lastEventId) return this.replayEvents(lastEventId); - } - if (this._streamMapping.get(this._standaloneSseStreamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Only one SSE stream is allowed per session")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Only one SSE stream is allowed per session"); - } - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(this._standaloneSseStreamId)?.controller === streamController) this._streamMapping.delete(this._standaloneSseStreamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - this._streamMapping.set(this._standaloneSseStreamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(this._standaloneSseStreamId); - try { - streamController.close(); - } catch {} - } - }); - keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } - /** - * Replays events that would have been sent after the specified event ID - * Only used when resumability is enabled - */ - async replayEvents(lastEventId) { - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error("Event store not configured")); - return this.createJsonErrorResponse(400, -32e3, "Event store not configured"); - } - try { - let streamId; - if (this._eventStore.getStreamIdForEventId) { - streamId = await this._eventStore.getStreamIdForEventId(lastEventId); - if (!streamId) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid event ID format")); - return this.createJsonErrorResponse(400, -32e3, "Invalid event ID format"); - } - if (this._streamMapping.get(streamId) !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Conflict: Stream already has an active connection")); - return this.createJsonErrorResponse(409, -32e3, "Conflict: Stream already has an active connection"); - } - } - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - let cancelled = false; - let replayedStreamId; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - cancelled = true; - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (replayedStreamId !== void 0 && this._streamMapping.get(replayedStreamId)?.controller === streamController) this._streamMapping.delete(replayedStreamId); - } - }); - const replayedEventIds = /* @__PURE__ */ new Set(); - replayedStreamId = await this._eventStore.replayEventsAfter(lastEventId, { send: async (eventId, message) => { - replayedEventIds.add(eventId); - if (!this.writeSSEEvent(streamController, encoder, message, eventId)) try { - streamController.close(); - } catch {} - } }); - if (this._closed || cancelled) { - try { - streamController.close(); - } catch {} - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - this._streamMapping.get(replayedStreamId)?.cleanup(); - this._streamMapping.set(replayedStreamId, { - controller: streamController, - encoder, - replayedEventIds, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - }); - if (replayedStreamId !== this._standaloneSseStreamId) { - if (![...this._requestToStreamMapping.values()].includes(replayedStreamId)) { - this._streamMapping.delete(replayedStreamId); - try { - streamController.close(); - } catch {} - } - } - if (this._streamMapping.get(replayedStreamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { headers }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(500, -32e3, "Error replaying events"); - } - } - /** - * Writes an event to an SSE stream via controller with proper formatting - */ - writeSSEEvent(controller, encoder, message, eventId) { - try { - let eventData = `event: message\n`; - if (eventId) eventData += `id: ${eventId}\n`; - eventData += `data: ${JSON.stringify(message)}\n\n`; - controller.enqueue(encoder.encode(eventData)); - return true; - } catch (error) { - this.onerror?.(error); - return false; - } - } - /** - * Handles unsupported requests (`PUT`, `PATCH`, etc.) - */ - handleUnsupportedRequest() { - this.onerror?.(/* @__PURE__ */ new Error("Method not allowed.")); - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: "Method not allowed." - }, - id: null - }, { - status: 405, - headers: { - Allow: "GET, POST, DELETE", - "Content-Type": "application/json" - } - }); - } - /** - * Handles `POST` requests containing JSON-RPC messages - */ - async handlePostRequest(req, options) { - try { - const acceptHeader = req.headers.get("accept"); - if (!acceptHeader?.includes("application/json") || !acceptHeader.includes("text/event-stream")) { - this.onerror?.(/* @__PURE__ */ new Error("Not Acceptable: Client must accept both application/json and text/event-stream")); - return this.createJsonErrorResponse(406, -32e3, "Not Acceptable: Client must accept both application/json and text/event-stream"); - } - if (!isJsonContentType(req.headers.get("content-type"))) { - this.onerror?.(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return this.createJsonErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const request = req; - let rawMessage; - if (options?.parsedBody === void 0) try { - rawMessage = await req.json(); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON"); - } - else rawMessage = options.parsedBody; - let messages; - try { - messages = Array.isArray(rawMessage) ? rawMessage.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(rawMessage)]; - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error: Invalid JSON-RPC message"); - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - const isInitializationRequest = messages.some((element) => isInitializeRequest(element)); - if (isInitializationRequest) { - if (this._initialized && this.sessionId !== void 0) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Server already initialized")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Server already initialized"); - } - if (messages.length > 1) { - this.onerror?.(/* @__PURE__ */ new Error("Invalid Request: Only one initialization request is allowed")); - return this.createJsonErrorResponse(400, -32600, "Invalid Request: Only one initialization request is allowed"); - } - this.sessionId = this.sessionIdGenerator?.(); - this._initialized = true; - if (this.sessionId && this._onsessioninitialized) await Promise.resolve(this._onsessioninitialized(this.sessionId)); - } - if (!isInitializationRequest) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - } - if (this._closed) return this.createJsonErrorResponse(404, -32001, "Session not found"); - if (!messages.some((element) => isJSONRPCRequest(element))) { - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - return new Response(null, { status: 202 }); - } - const streamId = crypto.randomUUID(); - const initRequest = messages.find((m) => isInitializeRequest(m)); - const clientProtocolVersion = initRequest ? initRequest.params.protocolVersion : req.headers.get("mcp-protocol-version") ?? DEFAULT_NEGOTIATED_PROTOCOL_VERSION; - if (this._enableJsonResponse) return new Promise((resolve) => { - this._streamMapping.set(streamId, { - resolveJson: resolve, - cleanup: () => { - this._streamMapping.delete(streamId); - } - }); - for (const message of messages) if (isJSONRPCRequest(message)) this._requestToStreamMapping.set(message.id, streamId); - for (const message of messages) this.onmessage?.(message, { - authInfo: options?.authInfo, - request - }); - }); - const encoder = new TextEncoder(); - let streamController; - let keepAliveTimer; - const readable = new ReadableStream({ - start: (controller) => { - streamController = controller; - }, - cancel: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - if (this._streamMapping.get(streamId)?.controller === streamController) this._streamMapping.delete(streamId); - } - }); - const headers = { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache, no-transform", - Connection: "keep-alive", - "X-Accel-Buffering": "no" - }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - for (const message of messages) if (isJSONRPCRequest(message)) { - this._streamMapping.set(streamId, { - controller: streamController, - encoder, - cleanup: () => { - if (keepAliveTimer !== void 0) clearInterval(keepAliveTimer); - this._streamMapping.delete(streamId); - try { - streamController.close(); - } catch {} - } - }); - this._requestToStreamMapping.set(message.id, streamId); - } - await this.writePrimingEvent(streamController, encoder, streamId, clientProtocolVersion); - for (const message of messages) { - let closeSSEStream; - let closeStandaloneSSEStream; - if (isJSONRPCRequest(message) && this._eventStore && this.supportsEmptySSEData(clientProtocolVersion)) { - closeSSEStream = () => { - this.closeSSEStream(message.id); - }; - closeStandaloneSSEStream = () => { - this.closeStandaloneSSEStream(); - }; - } - this.onmessage?.(message, { - authInfo: options?.authInfo, - request, - closeSSEStream, - closeStandaloneSSEStream - }); - } - if (this._streamMapping.get(streamId)?.controller === streamController) keepAliveTimer = this.startKeepAlive(streamController, encoder); - return new Response(readable, { - status: 200, - headers - }); - } catch (error) { - this.onerror?.(error); - return this.createJsonErrorResponse(400, -32700, "Parse error", { data: String(error) }); - } - } - /** - * Handles `DELETE` requests to terminate sessions - */ - async handleDeleteRequest(req) { - const sessionError = this.validateSession(req); - if (sessionError) return sessionError; - const protocolError = this.validateProtocolVersion(req); - if (protocolError) return protocolError; - try { - await Promise.resolve(this._onsessionclosed?.(this.sessionId)); - return new Response(null, { status: 200 }); - } finally { - await this.close(); - } - } - /** - * Validates session ID for non-initialization requests. - * Returns `Response` error if invalid, `undefined` otherwise - */ - validateSession(req) { - if (this.sessionIdGenerator === void 0) return; - if (!this._initialized) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Server not initialized")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Server not initialized"); - } - const sessionId = req.headers.get("mcp-session-id"); - if (!sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Bad Request: Mcp-Session-Id header is required")); - return this.createJsonErrorResponse(400, -32e3, "Bad Request: Mcp-Session-Id header is required"); - } - if (sessionId !== this.sessionId) { - this.onerror?.(/* @__PURE__ */ new Error("Session not found")); - return this.createJsonErrorResponse(404, -32001, "Session not found"); - } - } - /** - * Validates the `MCP-Protocol-Version` header on incoming requests. - * - * For initialization: Version negotiation handles unknown versions gracefully - * (server responds with its supported version). - * - * For subsequent requests with `MCP-Protocol-Version` header: - * - Accept if in supported list - * - 400 if unsupported - * - * For HTTP requests without the `MCP-Protocol-Version` header: - * - Accept and default to the version negotiated at initialization - */ - validateProtocolVersion(req) { - const protocolVersion = req.headers.get("mcp-protocol-version"); - if (protocolVersion !== null && !this._supportedProtocolVersions.includes(protocolVersion)) { - const error = `Bad Request: Unsupported protocol version: ${protocolVersion} (supported versions: ${this._supportedProtocolVersions.join(", ")})`; - this.onerror?.(new Error(error)); - return this.createJsonErrorResponse(400, -32e3, error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - for (const { cleanup } of this._streamMapping.values()) cleanup(); - this._streamMapping.clear(); - this._requestResponseMap.clear(); - this.onclose?.(); - } - /** - * Close an SSE stream for a specific request, triggering client reconnection. - * Use this to implement polling behavior during long-running operations - - * client will reconnect after the retry interval specified in the priming event. - */ - closeSSEStream(requestId) { - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) return; - const stream = this._streamMapping.get(streamId); - if (stream) stream.cleanup(); - } - /** - * Close the standalone `GET` SSE stream, triggering client reconnection. - * Use this to implement polling behavior for server-initiated notifications. - */ - closeStandaloneSSEStream() { - const stream = this._streamMapping.get(this._standaloneSseStreamId); - if (stream) stream.cleanup(); - } - async send(message, options) { - let requestId = options?.relatedRequestId; - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) requestId = message.id; - if (requestId === void 0) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request"); - let eventId; - if (this._eventStore) eventId = await this._eventStore.storeEvent(this._standaloneSseStreamId, message); - const standaloneSse = this._streamMapping.get(this._standaloneSseStreamId); - if (standaloneSse === void 0) return; - if (standaloneSse.controller && standaloneSse.encoder && (eventId === void 0 || !standaloneSse.replayedEventIds?.has(eventId))) this.writeSSEEvent(standaloneSse.controller, standaloneSse.encoder, message, eventId); - return; - } - const streamId = this._requestToStreamMapping.get(requestId); - if (!streamId) throw new Error(`No connection established for request ID: ${String(requestId)}`); - let stream = this._streamMapping.get(streamId); - if (!this._enableJsonResponse) { - let eventId; - if (this._eventStore) { - eventId = await this._eventStore.storeEvent(streamId, message); - stream = this._streamMapping.get(streamId); - } - if (stream?.controller && stream?.encoder && (eventId === void 0 || !stream.replayedEventIds?.has(eventId))) this.writeSSEEvent(stream.controller, stream.encoder, message, eventId); - } - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - this._requestResponseMap.set(requestId, message); - const relatedIds = [...this._requestToStreamMapping.entries()].filter(([_, sid]) => sid === streamId).map(([id]) => id); - if (relatedIds.every((id) => this._requestResponseMap.has(id))) { - if (!stream) { - if (this._enableJsonResponse) throw new Error(`No connection established for request ID: ${String(requestId)}`); - if (!this._eventStore) { - this.onerror?.(/* @__PURE__ */ new Error(`Response for request ID ${String(requestId)} is undeliverable: per-request stream is disconnected and no eventStore is configured`)); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - return; - } - if (this._enableJsonResponse && stream.resolveJson) { - const headers = { "Content-Type": "application/json" }; - if (this.sessionId !== void 0) headers["mcp-session-id"] = this.sessionId; - const responses = relatedIds.map((id) => this._requestResponseMap.get(id)); - if (responses.length === 1) stream.resolveJson(Response.json(responses[0], { - status: 200, - headers - })); - else stream.resolveJson(Response.json(responses, { - status: 200, - headers - })); - stream.cleanup(); - } else stream.cleanup(); - for (const id of relatedIds) { - this._requestResponseMap.delete(id); - this._requestToStreamMapping.delete(id); - } - } - } - } -}; - -//#endregion -//#region src/server/createMcpHandler.ts -/** -* The JSON-RPC id to echo on an entry-built error response: the body's `id` -* when the body is a single JSON-RPC request whose id is a string or number, -* `null` otherwise. Error responses must carry the id of the request they -* correspond to whenever it could be read; `null` is reserved for the cases -* where no single request id is determinable — unparseable bodies, body-less -* methods, notifications, posted responses and batch arrays. -*/ -function echoableRequestId(body) { - if (body === null || typeof body !== "object" || Array.isArray(body)) return null; - const { method, id } = body; - if (typeof method !== "string") return null; - return typeof id === "string" || typeof id === "number" ? id : null; -} -function jsonRpcErrorResponse(httpStatus, code, message, data, id = null) { - return Response.json({ - jsonrpc: "2.0", - error: { - code, - message, - ...data !== void 0 && { data } - }, - id - }, { status: httpStatus }); -} -function rejectionResponse(rejection, id = null) { - return jsonRpcErrorResponse(rejection.httpStatus, rejection.code, rejection.message, rejection.data, id); -} -function toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} -function internalServerErrorResponse(id = null) { - return jsonRpcErrorResponse(500, -32603, "Internal server error", void 0, id); -} -/** -* The entry's default legacy serving (`legacy: 'stateless'`): per-request -* stateless serving of 2025-era traffic using the same factory as the modern -* path. Exported as a standalone building block for hand-wired compositions -* (for example mounting legacy stateless serving on its own route next to a -* strict modern endpoint). -* -* Each POST is served by a fresh instance from the factory connected to a -* fresh streamable HTTP transport constructed with only -* `sessionIdGenerator: undefined` — the established stateless idiom, unchanged. -* Because serving is per-request and stateless, GET and DELETE (2025 session -* operations) are answered with `405` / `Method not allowed.`, exactly like the -* canonical stateless example. -* -* The optional `onerror` callback receives factory and serving failures on -* this leg (reporting only — the response stays the 500 internal-error body). -* The entry passes its own `onerror` here when expanding the default, so -* legacy-leg failures are never silently swallowed. -*/ -function createLegacyStatelessFallback(factory, onerror, keepAliveMs) { - return async (request, options) => { - if (request.method.toUpperCase() !== "POST") return jsonRpcErrorResponse(405, -32e3, "Method not allowed."); - try { - const product = await factory({ - era: "legacy", - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - requestInfo: request - }); - const transport = new WebStandardStreamableHTTPServerTransport({ - sessionIdGenerator: void 0, - ...keepAliveMs !== void 0 && { keepAliveMs } - }); - await product.connect(transport); - const teardown = () => { - transport.close().catch(() => {}); - product.close().catch(() => {}); - }; - request.signal?.addEventListener("abort", teardown, { once: true }); - const response = await transport.handleRequest(request, { - ...options?.authInfo !== void 0 && { authInfo: options.authInfo }, - ...options?.parsedBody !== void 0 && { parsedBody: options.parsedBody } - }); - if (response.body === null || mediaTypeEssence(response.headers.get("content-type")) !== "text/event-stream") { - teardown(); - return response; - } - const reader = response.body.getReader(); - let toreDown = false; - const completeExchange = () => { - if (!toreDown) { - toreDown = true; - teardown(); - } - }; - const monitoredBody = new ReadableStream({ - pull: async (controller) => { - try { - const { done, value } = await reader.read(); - if (done) { - completeExchange(); - controller.close(); - return; - } - if (value !== void 0) controller.enqueue(value); - } catch (error) { - completeExchange(); - controller.error(error); - } - }, - cancel: (reason) => { - completeExchange(); - return reader.cancel(reason).catch(() => {}); - } - }); - return new Response(monitoredBody, { - status: response.status, - statusText: response.statusText, - headers: response.headers - }); - } catch (error) { - try { - onerror?.(toError(error)); - } catch {} - return internalServerErrorResponse(echoableRequestId(options?.parsedBody)); - } - }; -} -function legacyStatelessFallback(factory, onerror) { - return createLegacyStatelessFallback(factory, onerror); -} -/** -* The entry's classification step: read the request body exactly once (unless -* a pre-parsed body is supplied) and classify the request with -* {@linkcode classifyInboundRequest}. This is the single code path behind both -* {@linkcode createMcpHandler}'s routing and the exported -* {@linkcode isLegacyRequest} predicate, so the two can never disagree. -* -* Pass `needsForward: false` when the caller never reads `forwardRequest` — -* the body-preserving clone is then skipped and `forwardRequest` is the -* (consumed) input request. -*/ -async function classifyEntryRequest(request, providedParsedBody, needsForward = true) { - const httpMethod = request.method.toUpperCase(); - let body; - let parsedBody = providedParsedBody; - let forwardRequest = request; - let unparseable = false; - if (httpMethod === "POST") { - if (parsedBody === void 0) { - if (needsForward) forwardRequest = request.clone(); - let bodyText; - try { - bodyText = await request.text(); - } catch { - return { step: "unreadable-body" }; - } - try { - body = bodyText.length === 0 ? void 0 : JSON.parse(bodyText); - } catch { - unparseable = true; - } - if (!unparseable && body !== void 0) parsedBody = body; - } else body = parsedBody; - if (unparseable || body === void 0) return { - step: "no-json-body", - forwardRequest - }; - } - return { - step: "classified", - outcome: classifyInboundRequest({ - httpMethod, - protocolVersionHeader: request.headers.get("mcp-protocol-version") ?? void 0, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0, - ...body !== void 0 && { body } - }), - body, - parsedBody, - forwardRequest - }; -} -/** -* Whether {@linkcode createMcpHandler} would route this request to its legacy -* (2025-era) serving rather than the modern (2026-07-28) path. -* -* Call it with just the request: `await isLegacyRequest(request)`. For a -* `POST` the body is read from an internal clone, so the request you pass -* stays fully readable for whichever handler you route it to — no second -* argument is needed. (In a Node `(req, res)` handler, build that `Request` -* with `toWebRequest(req)` from `@modelcontextprotocol/node`; behind a body -* parser, which has already drained the Node stream, build it as -* `toWebRequest(req, req.body)` so the bytes come from the parsed body — -* either way the predicate still takes just the request.) The optional -* `parsedBody` is a perf escape hatch for a body you already hold parsed: -* pass it and the predicate classifies from the value directly, reading and -* cloning nothing. It is needed, not just faster, when the request's own -* body was already read — the internal clone is then impossible (cloning a -* used body throws a `TypeError`), so such a single-argument call rejects -* instead of guessing. -* -* This is the entry's own classification step exported as a predicate — it -* runs exactly the code `createMcpHandler` runs to make the routing decision, -* not a re-implementation — so a hand-wired composition that branches on it -* can never disagree with the entry. It is classification only: hand-wired -* compositions must validate Content-Type themselves (415 for POSTs whose -* media type is not `application/json`, via {@linkcode isJsonContentType}) -* before dispatching either leg — routing the legacy leg into the SDK -* transports gets their built-in check, but a custom modern leg has none. Use it to keep an existing legacy -* deployment (for example a sessionful streamable HTTP wiring) serving 2025 -* traffic next to a strict modern endpoint, now that the entry has no -* handler-valued `legacy` option: -* -* ```ts -* import { createMcpHandler, isLegacyRequest } from '@modelcontextprotocol/server'; -* -* const modern = createMcpHandler(factory, { legacy: 'reject' }); -* -* export default { -* async fetch(request: Request): Promise { -* if (await isLegacyRequest(request)) { -* // e.g. an existing sessionful WebStandardStreamableHTTPServerTransport wiring -* return myExistingLegacyHandler(request); -* } -* return modern.fetch(request); -* } -* }; -* ``` -* -* Semantics (identical to the entry's routing): -* -* - Returns `true` only for requests with no per-request `_meta` envelope -* claim: claim-less POSTs (including the `initialize` handshake and 2025-era -* notification POSTs without a modern protocol-version header), body-less -* GET/DELETE session operations, all-legacy JSON-RPC batch arrays, posted -* JSON-RPC responses, and POSTs whose body is empty or not valid JSON. -* - Returns `false` for everything the modern path answers, including its -* validation-ladder rejections: a request carrying the envelope claim (even -* one naming a revision the endpoint does not serve — the modern path -* answers it with the unsupported-protocol-version error), a malformed -* envelope behind a present claim (answered `-32602`), a request whose -* `MCP-Protocol-Version` header names a modern revision but that lacks the -* envelope (`-32602`), and header/body mismatches (`-32020`). Consumers -* routing on the predicate must send `false` traffic to the modern handler, -* never to a legacy handler — the modern path owns those error answers. -* - `server/discover` probes sent by negotiating clients always carry the -* envelope claim, so they are never legacy; a hand-built claim-less POST to -* a method named `server/discover` has no claim and classifies legacy, -* exactly as the entry itself routes it. -*/ -async function isLegacyRequest(request, parsedBody) { - const classified = await classifyEntryRequest(parsedBody === void 0 && request.method.toUpperCase() === "POST" ? request.clone() : request, parsedBody, false); - return classified.step === "no-json-body" || classified.step === "classified" && classified.outcome.kind === "legacy"; -} -/** -* Creates an HTTP handler that serves the 2026-07-28 protocol revision from a -* per-request server factory and, by default, falls back to old-school -* stateless serving for 2025-era traffic. Pass `legacy: 'reject'` for a -* modern-only strict endpoint. -* -* Mounting: `handler.fetch` is the web-standard face (Cloudflare Workers, -* Deno, Bun, Hono's `c.req.raw`); for Express/Fastify/plain `node:http`, wrap -* the handler once with `toNodeHandler(handler)` from -* `@modelcontextprotocol/node`. When mounting bare on a fetch-native runtime, -* put Origin/Host validation in front of the handler — the entry itself is -* deliberately validation-free: -* -* ```ts -* import { hostHeaderValidationResponse, originValidationResponse, localhostAllowedHostnames, localhostAllowedOrigins } from '@modelcontextprotocol/server'; -* -* export default { -* async fetch(request: Request): Promise { -* const rejected = -* hostHeaderValidationResponse(request, localhostAllowedHostnames()) ?? -* originValidationResponse(request, localhostAllowedOrigins()); -* return rejected ?? handler.fetch(request); -* } -* }; -* ``` -* -* Use ONE factory for both legs: the same tools/resources/prompts definition -* backs the modern path and the stateless legacy fallback, so the two eras can -* never drift apart. To keep an existing legacy deployment (for example a -* sessionful streamable HTTP wiring) serving 2025 traffic instead of the -* stateless fallback, route in user land with {@linkcode isLegacyRequest} in -* front of a strict handler — see that predicate's documentation for the -* pattern. Power users composing transport-neutral routing can also use the -* exported building blocks directly: {@linkcode classifyInboundRequest} for -* the era decision and `PerRequestHTTPServerTransport` for single-exchange -* serving — such compositions must reject POSTs whose Content-Type media type -* is not `application/json` (415) before parsing the body, using -* {@linkcode isJsonContentType}; neither building block performs this -* validation itself. -* -* The entry performs no token verification: `authInfo` given to `fetch` is -* passed through to handlers and the factory as-is and is never derived from -* request headers. -*/ -function createMcpHandler(factory, options = {}) { - const { legacy, onerror, responseMode } = options; - if (typeof legacy === "function") throw new TypeError("The 'legacy' option only accepts 'stateless' or 'reject', not a handler function. To serve 2025-era traffic with your own handler, route in user land with the exported isLegacyRequest(request) predicate in front of a strict (legacy: 'reject') handler."); - /** Modern per-request instances with an exchange still in flight (close() tears these down). */ - const inflight = /* @__PURE__ */ new Set(); - let closed = false; - const reportError = (error) => { - try { - onerror?.(error); - } catch {} - }; - const bus = options.bus ?? new InMemoryServerEventBus(reportError); - const notify = createServerNotifier(bus); - const listenRouter = createListenRouter({ - bus, - maxSubscriptions: options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS, - keepAliveMs: options.keepAliveMs ?? DEFAULT_SSE_KEEP_ALIVE_MS, - onerror: reportError - }); - if (responseMode === "json") console.warn("responseMode: 'json' drops mid-call notifications. subscriptions/listen streams are always served over SSE regardless; other notifications emitted before a result are dropped."); - const legacyHandler = legacy === "reject" ? void 0 : createLegacyStatelessFallback(factory, reportError, options.keepAliveMs); - async function serveModern(route, request, authInfo) { - const claimedRevision = route.classification.revision; - if (claimedRevision === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedRevision)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedRevision ?? "unknown" - }); - reportError(error); - return jsonRpcErrorResponse(400, error.code, error.message, error.data, echoableRequestId(route.message)); - } - const stdHeaderRejection = validateStandardRequestHeaders({ - httpMethod: request.method, - mcpMethodHeader: request.headers.get("mcp-method") ?? void 0, - mcpNameHeader: request.headers.get("mcp-name") ?? void 0 - }, route); - if (stdHeaderRejection !== void 0) { - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${stdHeaderRejection.cell}): ${stdHeaderRejection.message}`)); - return rejectionResponse(stdHeaderRejection, echoableRequestId(route.message)); - } - const meta = route.messageKind === "request" ? requestMetaOf(route.message.params) : void 0; - const declaredClientCapabilities = meta?.[CLIENT_CAPABILITIES_META_KEY]; - if (route.messageKind === "request") { - const required = requiredClientCapabilitiesForRequest(route.message.method); - if (required !== void 0) { - const missing = missingClientCapabilities(required, declaredClientCapabilities); - if (missing !== void 0) { - const error = new MissingRequiredClientCapabilityError({ requiredCapabilities: missing }); - reportError(error); - return jsonRpcErrorResponse(httpStatusForErrorCode(error.code, "ladder"), error.code, error.message, error.data, route.message.id); - } - } - } - const product = await factory({ - era: "modern", - ...authInfo !== void 0 && { authInfo }, - requestInfo: request - }); - const server = product instanceof McpServer ? product.server : product; - if (route.messageKind === "request" && route.message.method === "subscriptions/listen") { - const capabilities = server.getCapabilities(); - const serverInfo = serverIdentityOf(server); - product.close().catch(reportError); - return listenRouter.serve(route.message, request.signal, capabilities, serverInfo); - } - if (route.messageKind === "request" && route.message.method === "tools/call" && product instanceof McpServer) { - const callParams = route.message.params; - const toolName = typeof callParams?.name === "string" ? callParams.name : void 0; - const inputSchema = toolName === void 0 ? void 0 : product.toolInputSchemaJson(toolName); - if (inputSchema !== void 0) { - const scan = scanXMcpHeaderDeclarations(inputSchema); - if (scan.valid && scan.declarations.length > 0) { - const rejection = validateMcpParamHeaders(scan.declarations, callParams?.arguments, request.headers); - if (rejection !== void 0) { - product.close().catch(reportError); - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${rejection.cell}): ${rejection.message}`)); - return rejectionResponse(rejection, route.message.id); - } - } - } - } - setNegotiatedProtocolVersion(server, claimedRevision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (meta !== void 0) seedClientIdentityFromEnvelope(server, { - clientInfo: meta[CLIENT_INFO_META_KEY], - clientCapabilities: declaredClientCapabilities - }); - const previousOnClose = server.onclose; - inflight.add(server); - server.onclose = () => { - inflight.delete(server); - previousOnClose?.(); - }; - try { - const response = await invoke(product, route.message, { - classification: route.classification, - request, - ...authInfo !== void 0 && { authInfo }, - ...responseMode !== void 0 && { responseMode }, - ...options.keepAliveMs !== void 0 && { keepAliveMs: options.keepAliveMs } - }); - if (route.messageKind === "notification") queueMicrotask(() => void server.close().catch(() => {})); - return response; - } catch (error) { - if (error instanceof SdkError && error.code === SdkErrorCode.ConnectionClosed) return new Response(null, { status: 499 }); - await server.close().catch(() => {}); - inflight.delete(server); - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(route.message)); - } - } - async function serveLegacyRoute(route, forwardRequest, authInfo, parsedBody) { - if (legacyHandler !== void 0) return legacyHandler(forwardRequest, { - ...authInfo !== void 0 && { authInfo }, - ...parsedBody !== void 0 && { parsedBody } - }); - const strict = modernOnlyStrictRejection(route, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (strict === void 0) return new Response(null, { status: 202 }); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only endpoint (${strict.cell}): ${strict.message}`)); - return rejectionResponse(strict, echoableRequestId(parsedBody)); - } - async function handle(request, requestOptions) { - const authInfo = requestOptions?.authInfo; - if (request.method.toUpperCase() === "POST" && !isJsonContentType(request.headers.get("content-type"))) { - reportError(/* @__PURE__ */ new Error("Unsupported Media Type: Content-Type must be application/json")); - return jsonRpcErrorResponse(415, -32e3, "Unsupported Media Type: Content-Type must be application/json"); - } - const classified = await classifyEntryRequest(request, requestOptions?.parsedBody); - if (classified.step === "unreadable-body") return jsonRpcErrorResponse(400, -32700, "Parse error: the request body could not be read"); - if (classified.step === "no-json-body") { - if (legacyHandler !== void 0) return legacyHandler(classified.forwardRequest, { ...authInfo !== void 0 && { authInfo } }); - return jsonRpcErrorResponse(400, -32700, "Parse error: the request body is not valid JSON"); - } - const { outcome, body, parsedBody, forwardRequest } = classified; - try { - switch (outcome.kind) { - case "reject": - reportError(/* @__PURE__ */ new Error(`Rejected inbound request (${outcome.cell}): ${outcome.message}`)); - return rejectionResponse(outcome, echoableRequestId(body)); - case "modern": return await serveModern(outcome, request, authInfo); - case "legacy": return await serveLegacyRoute(outcome, forwardRequest, authInfo, parsedBody); - } - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(body)); - } - } - const fetchFace = async (request, requestOptions) => { - if (closed) throw new Error("This MCP handler has been closed"); - try { - return await handle(request, requestOptions); - } catch (error) { - reportError(toError(error)); - return internalServerErrorResponse(echoableRequestId(requestOptions?.parsedBody)); - } - }; - return { - fetch: fetchFace, - notify, - bus, - close: async () => { - closed = true; - listenRouter.closeAll(); - const closing = [...inflight].map((server) => server.close().catch(() => {})); - inflight.clear(); - await Promise.all(closing); - } - }; -} - -//#endregion -//#region src/server/middleware/bearerAuth.ts -function headerQuotedValue(value) { - return value.replaceAll(/[\\"]/g, String.raw`\$&`).replaceAll(/[^\u0020-\u007E]/g, " "); -} -function buildWwwAuthenticateHeader(errorCode, description, requiredScopes, resourceMetadataUrl) { - let header = `Bearer error="${headerQuotedValue(errorCode)}", error_description="${headerQuotedValue(description)}"`; - if (requiredScopes.length > 0) header += `, scope="${requiredScopes.join(" ")}"`; - if (resourceMetadataUrl) header += `, resource_metadata="${resourceMetadataUrl}"`; - return header; -} -/** -* Validate a raw `Authorization` header value as a Bearer token and return -* the verified {@link AuthInfo}. -* -* The runtime-neutral core of Bearer authentication: it parses the header, -* runs the verifier, enforces `requiredScopes`, and rejects tokens without an -* expiration or past it. On any failure it throws an {@link OAuthError} — -* pass that to {@link bearerAuthChallengeResponse} for the matching HTTP -* answer, or use {@link requireBearerAuth} to get both steps as one call. -* -* Framework adapters build on this: `requireBearerAuth` from -* `@modelcontextprotocol/express` feeds it `req.headers.authorization`. -*/ -async function verifyBearerToken(authorizationHeader, options) { - const { verifier, requiredScopes = [] } = options; - if (!authorizationHeader) throw new OAuthError(OAuthErrorCode.InvalidToken, "Missing Authorization header"); - const [type, token] = authorizationHeader.split(" "); - if (type?.toLowerCase() !== "bearer" || !token) throw new OAuthError(OAuthErrorCode.InvalidToken, "Invalid Authorization header format, expected 'Bearer TOKEN'"); - const authInfo = await verifier.verifyAccessToken(token); - if (requiredScopes.length > 0) { - if (!requiredScopes.every((scope) => authInfo.scopes.includes(scope))) throw new OAuthError(OAuthErrorCode.InsufficientScope, "Insufficient scope"); - } - if (typeof authInfo.expiresAt !== "number" || Number.isNaN(authInfo.expiresAt)) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has no expiration time"); - else if (authInfo.expiresAt < Date.now() / 1e3) throw new OAuthError(OAuthErrorCode.InvalidToken, "Token has expired"); - return authInfo; -} -/** -* Build the HTTP answer for a Bearer authentication failure. -* -* Maps an {@link OAuthError} to its status — `401` for `invalid_token` and -* `403` for `insufficient_scope` (both carrying the `WWW-Authenticate: Bearer …` -* challenge, with `resource_metadata` when configured so clients can discover -* the Authorization Server), `500` for `server_error`, `400` for anything -* else. A non-`OAuthError` value answers `500 server_error`. The body is the -* OAuth error JSON. -*/ -function bearerAuthChallengeResponse(error, options) { - const { requiredScopes = [], resourceMetadataUrl } = options ?? {}; - if (!(error instanceof OAuthError)) { - const serverError = new OAuthError(OAuthErrorCode.ServerError, "Internal Server Error"); - return Response.json(serverError.toResponseObject(), { status: 500 }); - } - switch (error.code) { - case OAuthErrorCode.InvalidToken: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 401, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.InsufficientScope: { - const challenge = buildWwwAuthenticateHeader(error.code, error.message, requiredScopes, resourceMetadataUrl); - return Response.json(error.toResponseObject(), { - status: 403, - headers: { "WWW-Authenticate": challenge } - }); - } - case OAuthErrorCode.ServerError: return Response.json(error.toResponseObject(), { status: 500 }); - default: return Response.json(error.toResponseObject(), { status: 400 }); - } -} -/** -* Require a valid Bearer token on web-standard requests. -* -* The framework-free counterpart of `requireBearerAuth` from -* `@modelcontextprotocol/express`, for hosts whose HTTP surface is a -* `fetch(request)` handler — Cloudflare Workers, Deno, Bun, Hono. The -* returned gate resolves to the verified {@link AuthInfo}, or to the -* ready-to-return challenge `Response` when the request must be refused. -* -* @example -* ```ts source="./bearerAuth.examples.ts#requireBearerAuth_fetchGate" -* const gate = requireBearerAuth({ verifier, requiredScopes: ['mcp'] }); -* -* async function fetchHandler(request: Request): Promise { -* const auth: AuthInfo | Response = await gate(request); -* if (auth instanceof Response) return auth; -* return handler.fetch(request, { authInfo: auth }); -* } -* ``` -*/ -function requireBearerAuth(options) { - const { verifier, requiredScopes = [], resourceMetadataUrl } = options; - const resolved = { - verifier, - requiredScopes, - resourceMetadataUrl - }; - return async (request) => { - const [authorizationHeader] = (request.headers.get("authorization") ?? "").split(","); - try { - return await verifyBearerToken(authorizationHeader || void 0, resolved); - } catch (error) { - return bearerAuthChallengeResponse(error, resolved); - } - }; -} - -//#endregion -//#region src/server/middleware/hostHeaderValidation.ts -/** -* Parse and validate a `Host` header against an allowlist of hostnames (port-agnostic). -* -* - Input host header may include a port (e.g. `localhost:3000`) or IPv6 brackets (e.g. `[::1]:3000`). -* - Allowlist items should be hostnames only (no ports). For IPv6, include brackets (e.g. `[::1]`). -*/ -function validateHostHeader(hostHeader, allowedHostnames) { - if (!hostHeader) return { - ok: false, - errorCode: "missing_host", - message: "Missing Host header" - }; - let hostname; - try { - hostname = new URL(`http://${hostHeader}`).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_host_header", - message: `Invalid Host header: ${hostHeader}`, - hostHeader - }; - } - if (!allowedHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_host", - message: `Invalid Host: ${hostname}`, - hostHeader, - hostname - }; - return { - ok: true, - hostname - }; -} -/** -* Convenience allowlist for `localhost` DNS rebinding protection. -*/ -function localhostAllowedHostnames() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for DNS rebinding protection. -* @example -* ```ts source="./hostHeaderValidation.examples.ts#hostHeaderValidationResponse_basicUsage" -* const result = validateHostHeader(req.headers.get('host'), ['localhost']); -* ``` -*/ -function hostHeaderValidationResponse(req, allowedHostnames) { - const result = validateHostHeader(req.headers.get("host"), allowedHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/middleware/oauthMetadata.ts -function checkIssuerUrl(issuer, allowInsecure) { - if (issuer.protocol !== "https:" && issuer.hostname !== "localhost" && issuer.hostname !== "127.0.0.1" && !allowInsecure) throw new Error("Issuer URL must be HTTPS"); - if (issuer.hash) throw new Error(`Issuer URL must not have a fragment: ${issuer}`); - if (issuer.search) throw new Error(`Issuer URL must not have a query string: ${issuer}`); -} -/** -* Derive the RFC 9728 Protected Resource Metadata document from -* {@link AuthMetadataOptions}, validating the Authorization Server issuer URL -* (HTTPS required outside localhost) in the process. -* -* `oauthMetadataResponse` and the Express `mcpAuthMetadataRouter` both build -* on this; use it directly when serving the document through your own -* routing — or call it once at startup to fail fast on a misconfigured -* issuer before any request arrives. -*/ -function buildOAuthProtectedResourceMetadata(options) { - checkIssuerUrl(new URL(options.oauthMetadata.issuer), options.dangerouslyAllowInsecureIssuerUrl); - return { - resource: options.resourceServerUrl.href, - authorization_servers: [options.oauthMetadata.issuer], - scopes_supported: options.scopesSupported, - resource_name: options.resourceName, - resource_documentation: options.serviceDocumentationUrl?.href - }; -} -/** -* Builds the RFC 9728 Protected Resource Metadata URL for a given MCP server -* URL by inserting `/.well-known/oauth-protected-resource` ahead of the path. -* -* @example -* ```ts -* getOAuthProtectedResourceMetadataUrl(new URL('https://api.example.com/mcp')) -* // → 'https://api.example.com/.well-known/oauth-protected-resource/mcp' -* ``` -*/ -function getOAuthProtectedResourceMetadataUrl(serverUrl) { - return new URL(protectedResourceMetadataPath(serverUrl), serverUrl).href; -} -/** The RFC 9728 path-aware well-known path for a resource URL. */ -function protectedResourceMetadataPath(resourceServerUrl) { - const rsPath = stripTrailingSlash(resourceServerUrl.pathname); - return `/.well-known/oauth-protected-resource${rsPath === "/" ? "" : rsPath}`; -} -function stripTrailingSlash(path) { - return path.length > 1 && path.endsWith("/") ? path.slice(0, -1) : path; -} -const ALLOWED_METHODS = "GET, HEAD, OPTIONS"; -function metadataDocumentResponse(request, metadata) { - if (request.method === "OPTIONS") { - const requestedHeaders = request.headers.get("access-control-request-headers"); - return new Response(null, { - status: 204, - headers: { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": ALLOWED_METHODS, - ...requestedHeaders === null ? {} : { - "Access-Control-Allow-Headers": requestedHeaders, - Vary: "Access-Control-Request-Headers" - } - } - }); - } - if (request.method !== "GET" && request.method !== "HEAD") { - const error = new OAuthError(OAuthErrorCode.MethodNotAllowed, `The method ${request.method} is not allowed for this endpoint`); - return Response.json(error.toResponseObject(), { - status: 405, - headers: { - Allow: ALLOWED_METHODS, - "Access-Control-Allow-Origin": "*" - } - }); - } - const response = Response.json(metadata, { headers: { "Access-Control-Allow-Origin": "*" } }); - return request.method === "HEAD" ? new Response(null, { - status: response.status, - headers: response.headers - }) : response; -} -/** -* Serve the two OAuth discovery documents an MCP server acting as a Resource -* Server exposes, from a web-standard `fetch(request)` handler: -* -* - `/.well-known/oauth-protected-resource[/]` — RFC 9728 Protected -* Resource Metadata, derived from the supplied options (path-aware: the -* resource URL's path is reflected in the route). -* - `/.well-known/oauth-authorization-server` — RFC 8414 Authorization -* Server Metadata, passed through verbatim. -* -* Returns the matched document `Response` (JSON with permissive CORS, `405` -* with an `Allow` header for non-GET methods, `204` for CORS preflight), or -* `undefined` when the request path is neither well-known route — fall -* through to your own routing. The framework-free counterpart of -* `mcpAuthMetadataRouter` from `@modelcontextprotocol/express`; pair it with -* `requireBearerAuth` and `getOAuthProtectedResourceMetadataUrl` so -* unauthenticated clients can discover the AS from the `401` challenge. -* -* @example -* ```ts source="./oauthMetadata.examples.ts#oauthMetadataResponse_fetchHandler" -* async function fetchHandler(request: Request): Promise { -* return oauthMetadataResponse(request, options) ?? serveMcp(request); -* } -* ``` -*/ -function oauthMetadataResponse(request, options) { - const requestPath = stripTrailingSlash(new URL(request.url).pathname); - if (requestPath === protectedResourceMetadataPath(options.resourceServerUrl)) return metadataDocumentResponse(request, buildOAuthProtectedResourceMetadata(options)); - if (requestPath === "/.well-known/oauth-authorization-server") { - buildOAuthProtectedResourceMetadata(options); - return metadataDocumentResponse(request, options.oauthMetadata); - } -} - -//#endregion -//#region src/server/middleware/originValidation.ts -/** -* Validate an `Origin` header against an allowlist of hostnames (port-agnostic). -* -* - A missing/empty `Origin` header passes: non-browser clients do not send one, -* and only browser-originated requests carry the header this check defends against. -* - Allowlist items are hostnames only (no scheme, no port), the same convention as -* `validateHostHeader`. For IPv6, include brackets (e.g. `[::1]`). -* - Any present value that cannot be parsed as an origin URL — including the literal -* `null` origin browsers send for opaque contexts — is rejected (deny on failure). -*/ -function validateOriginHeader(originHeader, allowedOriginHostnames) { - if (originHeader === null || originHeader === void 0 || originHeader === "") return { ok: true }; - let hostname; - try { - hostname = new URL(originHeader).hostname; - } catch { - return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - } - if (hostname === "") return { - ok: false, - errorCode: "invalid_origin_header", - message: `Invalid Origin header: ${originHeader}`, - originHeader - }; - if (!allowedOriginHostnames.includes(hostname)) return { - ok: false, - errorCode: "invalid_origin", - message: `Invalid Origin: ${hostname}`, - originHeader, - hostname - }; - return { - ok: true, - origin: originHeader, - hostname - }; -} -/** -* Convenience allowlist of localhost-class origin hostnames, mirroring -* `localhostAllowedHostnames`. -*/ -function localhostAllowedOrigins() { - return [ - "localhost", - "127.0.0.1", - "[::1]" - ]; -} -/** -* Web-standard `Request` helper for Origin validation: returns a `403` JSON-RPC -* error response when the request's `Origin` header is not allowed, and -* `undefined` when the request may proceed. -* -* ```ts -* const rejected = originValidationResponse(request, localhostAllowedOrigins()); -* if (rejected) return rejected; -* ``` -*/ -function originValidationResponse(req, allowedOriginHostnames) { - const result = validateOriginHeader(req.headers.get("origin"), allowedOriginHostnames); - if (result.ok) return void 0; - return Response.json({ - jsonrpc: "2.0", - error: { - code: -32e3, - message: result.message - }, - id: null - }, { - status: 403, - headers: { "Content-Type": "application/json" } - }); -} - -//#endregion -//#region src/server/requestStateCodec.ts -const PREFIX = "v1."; -function bytesToBase64Url(bytes) { - let bin = ""; - for (const b of bytes) bin += String.fromCodePoint(b); - return btoa(bin).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, ""); -} -function constantTimeTagEqual(a, b) { - if (a.length !== b.length) return false; - let r = 0; - for (let i = 0; i < a.length; i++) r |= a.codePointAt(i) ^ b.codePointAt(i); - return r === 0; -} -function base64UrlToBytes(s) { - const b64 = s.replaceAll("-", "+").replaceAll("_", "/"); - const bin = atob(b64); - const bytes = new Uint8Array(bin.length); - for (let i = 0; i < bin.length; i++) bytes[i] = bin.codePointAt(i); - return bytes; -} -/** -* Create an opt-in HMAC-SHA256 codec for the multi-round-trip `requestState` -* (protocol revision 2026-07-28). -* -* `requestState` round-trips through the client and is attacker-controlled -* input on re-entry. The SDK applies no protection of its own; this helper is -* the convenience implementation of the spec's integrity MUST so authors don't -* hand-roll HMAC. Wire shape: -* -* "v1." b64url({"p":,"exp":,"b":?}) "." b64url(mac) -* -* where `bindTag` is `b64url(HMAC(key, "mcp.requestState.bind:" + bind(ctx))[:16])` -* — the binding value is never embedded raw. -* -* The codec is **signed, not encrypted**: the body is integrity-protected but -* the client can base64url-decode it and read the payload (`p`) in clear. Do -* not put secrets in the payload; use an AEAD construction if confidentiality -* is required. The handler reads its payload back via the typed -* `ctx.mcpReq.requestState()` accessor — the seam has already run `verify` -* (integrity proven, payload decoded) by the time the handler is entered. -* -* Verification is fail-closed and constant-time (WebCrypto `subtle.verify` for -* the body MAC; a fixed-length XOR-accumulator compare for the bind tag). -* See `examples/mrtr/server.ts` for a worked end-to-end example. -* -* Design comparison (mcp.d `secureRequestState`, the peer SDK's reference -* implementation): mcp.d additionally offers an AES-256-GCM encrypted mode and -* derives independent cipher / bind-HMAC sub-keys from the operator secret via -* HKDF-SHA256, with an auto-generated per-process ephemeral key when none is -* supplied. This codec deliberately ships only the signed mode and a single -* keyed HMAC (domain-separated by input prefix) — HKDF sub-key derivation and -* an encrypted mode are intentionally out of scope for the initial release. -*/ -function createRequestStateCodec(options) { - const subtle = globalThis.crypto?.subtle; - if (subtle === void 0) throw new TypeError("createRequestStateCodec requires the Web Crypto API (globalThis.crypto.subtle); see https://ts.sdk.modelcontextprotocol.io/v2/troubleshooting for the Node.js polyfill instructions"); - const keyBytes = typeof options.key === "string" ? new TextEncoder().encode(options.key) : Uint8Array.from(options.key); - if (keyBytes.byteLength < 32) throw new RangeError(`createRequestStateCodec: key must be at least 32 bytes (got ${keyBytes.byteLength})`); - const ttlSeconds = options.ttlSeconds ?? 600; - if (!Number.isFinite(ttlSeconds)) throw new RangeError("createRequestStateCodec: ttlSeconds must be a finite number"); - const bind = options.bind; - let cryptoKey; - const importedKey = () => cryptoKey ??= subtle.importKey("raw", keyBytes, { - name: "HMAC", - hash: "SHA-256" - }, false, ["sign", "verify"]); - const utf8 = new TextEncoder(); - const BIND_LABEL = "mcp.requestState.bind:"; - const bindTag = async (value) => { - return bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(BIND_LABEL + value))).slice(0, 16)); - }; - return { - async mint(payload, ctx) { - const envelope = { - p: payload, - exp: Math.floor(Date.now() / 1e3) + ttlSeconds - }; - if (bind !== void 0) { - if (ctx === void 0) throw new TypeError("createRequestStateCodec: mint() requires ctx when a bind callback is configured"); - envelope.b = await bindTag(bind(ctx)); - } - const body = bytesToBase64Url(utf8.encode(JSON.stringify(envelope))); - return `${PREFIX}${body}.${bytesToBase64Url(new Uint8Array(await subtle.sign("HMAC", await importedKey(), utf8.encode(PREFIX + body))))}`; - }, - async verify(state, ctx) { - const dot = state.lastIndexOf("."); - if (!state.startsWith(PREFIX) || dot <= 3) throw new Error("malformed"); - const body = state.slice(3, dot); - let macBytes; - try { - macBytes = base64UrlToBytes(state.slice(dot + 1)); - } catch { - throw new Error("malformed"); - } - if (!await subtle.verify("HMAC", await importedKey(), macBytes, utf8.encode(PREFIX + body))) throw new Error("mac"); - let envelope; - try { - envelope = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(base64UrlToBytes(body))); - } catch { - throw new Error("malformed"); - } - if (typeof envelope.exp !== "number" || envelope.exp < Math.floor(Date.now() / 1e3)) throw new Error("expired"); - if (bind !== void 0) { - const expected = await bindTag(bind(ctx)); - if (envelope.b === void 0 || !constantTimeTagEqual(envelope.b, expected)) throw new Error("bind"); - } else if (envelope.b !== void 0) throw new Error("bind"); - return envelope.p; - } - }; -} - -//#endregion -//#region src/fromJsonSchema.ts -let _defaultValidator; -function dist_fromJsonSchema(schema, validator) { - return fromJsonSchema$1(schema, validator ?? (_defaultValidator ??= new DefaultJsonSchemaValidator())); -} - -//#endregion - -//# sourceMappingURL=index.mjs.map -const mcpApps = Object.freeze([ - { - "html": "\n\n \n \n \n Service status\n \n \n \n
        \n
        MCP App example
        \n

        No service selected

        \n
        unknown
        \n

        Invoke the readiness tool to inspect a service.

        \n
          \n \n \n \n \n

          \n
          \n \n\n", - "mimeType": "text/html;profile=mcp-app", - "name": "status", - "resourceUri": "ui://mcp-app-example/status.html" - } -]); - -/* export default */ const mcp_status_073c1634_0 = (mcpApps); - -// Generated by agent-bundle. Do not edit. -const meta_name = "mcp-app-example"; -const packageName = "@agent-bundle-example/mcp-app"; -const packageVersion = undefined; -const meta_version = "1.0.0"; -const meta_meta = Object.freeze({ - name: meta_name, - packageName: packageName, - packageVersion: packageVersion, - version: meta_version -}); -/* export default */ const _agent_bundle_virtual_meta = ((/* unused pure expression or super */ null && (meta_meta))); - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - - - - -const app = mcp_status_073c1634_0["0"]; -if (app === undefined) throw new Error('Expected the status MCP App.'); -const serviceCatalog = Object.freeze({ - compiler: healthyCompilerStatus, - 'payments-api': Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'P95 latency', - status: 'failing' - }) - ]), - service: 'payments-api', - status: 'degraded', - summary: 'Payment latency is above the release threshold.' - }) -}); -const createStatusServer = ()=>{ - // The compiler stamps this project's identity into `agent-bundle/meta`, so - // the wire identity cannot drift from the config or package.json. - const server = new mcp_DXXb3Vv3_McpServer({ - name: meta_name, - version: (/* inlined export .version */"1.0.0") - }); - server.registerResource(app.name, app.resourceUri, { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - mimeType: app.mimeType - }, async (uri)=>({ - contents: [ - { - mimeType: app.mimeType, - text: app.html, - uri: uri.href - } - ] - })); - server.registerTool('show-status', { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - description: 'Show the health of one example service.', - inputSchema: schemas_object({ - service: schemas_enum([ - 'compiler', - 'payments-api' - ]) - }) - }, async ({ service })=>{ - const result = serviceCatalog[service]; - return { - _meta: { - ui: { - resourceUri: app.resourceUri - } - }, - content: [ - { - text: result.summary, - type: 'text' - } - ], - structuredContent: result - }; - }); - return server; -}; -/** - * Default-exported server factory: `agent-bundle build` detects it and wraps - * this entry in the framework stdio lifecycle shell (console-to-stderr guard, - * SIGINT/SIGTERM handling, stdin-EOF exit, bounded shutdown, heartbeat). - */ /* export default */ const mcp_status = (createStatusServer); - - - - - -//#region src/server/stdio.ts -/** -* Server transport for stdio: this communicates with an MCP client by reading from the current process' `stdin` and writing to `stdout`. -* -* This transport is only available in Node.js environments. -* -* @example -* ```ts source="./stdio.examples.ts#StdioServerTransport_basicUsage" -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }); -* const transport = new StdioServerTransport(); -* await server.connect(transport); -* ``` -*/ -var stdio_StdioServerTransport = class { - _readBuffer; - _started = false; - _closed = false; - constructor(_stdin = node_process.stdin, _stdout = node_process.stdout, options) { - this._stdin = _stdin; - this._stdout = _stdout; - this._readBuffer = new ReadBuffer({ maxBufferSize: options?.maxBufferSize }); - } - onclose; - onerror; - onmessage; - _ondata = (chunk) => { - try { - this._readBuffer.append(chunk); - this.processReadBuffer(); - } catch (error) { - this.onerror?.(error); - this.close().catch(() => {}); - } - }; - _onerror = (error) => { - this.onerror?.(error); - }; - _onstdouterror = (error) => { - this.onerror?.(error); - this.close().catch(() => {}); - }; - /** - * Starts listening for messages on `stdin`. - */ - async start() { - if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically."); - this._started = true; - this._stdin.on("data", this._ondata); - this._stdin.on("error", this._onerror); - this._stdout.on("error", this._onstdouterror); - } - processReadBuffer() { - while (true) try { - const message = this._readBuffer.readMessage(); - if (message === null) break; - this.onmessage?.(message); - } catch (error) { - this.onerror?.(error); - } - } - async close() { - if (this._closed) return; - this._closed = true; - this._stdin.off("data", this._ondata); - this._stdin.off("error", this._onerror); - this._stdout.off("error", this._onstdouterror); - if (this._stdin.listenerCount("data") === 0) this._stdin.pause(); - this._readBuffer.clear(); - this.onclose?.(); - } - send(message) { - if (this._closed) return Promise.reject(/* @__PURE__ */ new Error("StdioServerTransport is closed")); - return new Promise((resolve, reject) => { - const json = serializeMessage(message); - let settled = false; - const onError = (error) => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - reject(error); - }; - const onDrain = () => { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - this._stdout.off("drain", onDrain); - resolve(); - }; - this._stdout.once("error", onError); - if (this._stdout.write(json)) { - if (settled) return; - settled = true; - this._stdout.off("error", onError); - resolve(); - } else if (!settled) this._stdout.once("drain", onDrain); - }); - } -}; - -//#endregion -//#region src/server/serveStdio.ts -/** -* How long the probe-discard path waits for the probe instance to answer the -* requests it was delivered before closing it. The wait normally settles as -* soon as the DiscoverResult is handed to the wire (or immediately, when a -* delivered cancellation already settled the probe); the bound is a backstop -* so no edge can ever hold the connection's inbound pump indefinitely behind -* the discard. -*/ -const DISCARD_ANSWER_TIMEOUT_MS = 3e3; -/** -* The transport a pinned instance is connected to: a thin channel that writes -* through to the entry-owned wire transport and receives the messages the -* entry forwards. The wire transport itself is never handed to an instance — -* that is what lets the entry discard an optimistic probe instance (close the -* channel) without tearing down the connection. -*/ -var StdioConnectionChannel = class { - onclose; - onerror; - onmessage; - _closed = false; - /** Request ids the entry delivered to the instance that the instance has not yet answered. */ - _pendingRequests = /* @__PURE__ */ new Set(); - _drainWaiters = []; - constructor(_wire, _onInstanceClose, _outboundIntercept) { - this._wire = _wire; - this._onInstanceClose = _onInstanceClose; - this._outboundIntercept = _outboundIntercept; - } - async start() {} - async send(message, options) { - if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) { - const { id } = message; - if (id !== void 0) this._settle(id); - } - if (this._closed) return; - if (this._outboundIntercept?.(message) === "handled") return; - return this._wire.send(message, options); - } - setProtocolVersion = (version) => { - this._wire.setProtocolVersion?.(version); - }; - /** Forwards one inbound message to the connected instance. */ - deliver(message, extra) { - if (this._closed) return; - if (isJSONRPCRequest(message)) this._pendingRequests.add(message.id); - else if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0) this._settle(cancelledId); - } - this.onmessage?.(message, extra); - } - /** - * Resolves once every request delivered to the instance has been answered - * through {@linkcode send}, settled by a delivered cancellation, or the - * channel has been closed and nothing further can be answered. The wait is - * bounded by `timeoutMs` as a backstop so no edge can hold the caller - * indefinitely; resolves `false` only when the bound elapsed with requests - * still unanswered. Used by the probe-discard path so a probe request the - * entry accepted is never silently dropped. - */ - async whenRequestsAnswered(timeoutMs) { - if (this._closed || this._pendingRequests.size === 0) return true; - return await new Promise((resolve) => { - const waiter = () => { - clearTimeout(timer); - resolve(true); - }; - const timer = setTimeout(() => { - this._drainWaiters = this._drainWaiters.filter((pending) => pending !== waiter); - resolve(false); - }, timeoutMs); - this._drainWaiters.push(waiter); - }); - } - async close() { - if (this._closed) return; - this._closed = true; - this._pendingRequests.clear(); - this._releaseDrainWaiters(); - try { - this._onInstanceClose(); - } finally { - this.onclose?.(); - } - } - _settle(id) { - this._pendingRequests.delete(id); - if (this._pendingRequests.size === 0) this._releaseDrainWaiters(); - } - _releaseDrainWaiters() { - const waiters = this._drainWaiters; - this._drainWaiters = []; - for (const waiter of waiters) waiter(); - } -}; -/** -* Classifies one message of the opening exchange with the same body-primary -* rules the HTTP entry applies per request: `initialize` is the legacy -* handshake unless it carries a valid modern envelope claim; a present claim -* is validated (never silently ignored); a claim-less message is 2025-era -* traffic. There is no header layer on stdio, so the body is the only signal. -*/ -function classifyOpeningMessage(message) { - const params = message.params; - if (message.method === "initialize" && !carriesValidModernEnvelopeClaim(params)) { - const requestedVersion = params !== null && typeof params === "object" && typeof params.protocolVersion === "string" ? params.protocolVersion : void 0; - return { - kind: "legacy", - reason: "initialize", - ...requestedVersion !== void 0 && { requestedVersion } - }; - } - if (!hasEnvelopeClaim(params)) return { - kind: "legacy", - reason: "no-claim" - }; - const meta = requestMetaOf(params); - const firstIssue = (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0]; - if (firstIssue !== void 0) return { - kind: "invalid-envelope", - issue: firstIssue - }; - const claimedVersion = envelopeClaimVersion(params); - if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) return { - kind: "unsupported-revision", - requested: claimedVersion ?? "unknown" - }; - return { - kind: "modern", - revision: claimedVersion, - classification: { - era: "modern", - revision: claimedVersion - } - }; -} -/** -* Serves MCP over stdio from a server factory, owning the era decision for -* the connection: the opening exchange selects the era, ONE instance from the -* factory is pinned for the connection lifetime, and everything after passes -* straight through to it. See the module documentation for the opening rules. -* -* ```ts -* import { serveStdio } from '@modelcontextprotocol/server/stdio'; -* -* serveStdio(() => { -* const server = new McpServer({ name: 'my-server', version: '1.0.0' }, { capabilities: { tools: {} } }); -* // register tools/resources/prompts once — the same factory serves both eras -* return server; -* }); -* ``` -*/ -function serveStdio(factory, options = {}) { - const legacyMode = options.legacy ?? "serve"; - const wire = options.transport ?? new stdio_StdioServerTransport(); - let state = { phase: "opening" }; - /** Channel currently being discarded (its close must not tear the connection down). */ - let discarding; - let closing = false; - /** - * Whether the connection has been torn down (`handle.close()` or the wire - * closing). The opening arms re-check this after every await: a close can - * race factory construction, and the continuation must neither resurrect - * the connection state nor keep a late-resolved instance around. - */ - const isTornDown = () => closing || state.phase === "closed"; - const reportError = (error) => { - try { - options.onerror?.(error); - } catch {} - }; - const writeErrorResponse = (id, code, message, data) => wire.send({ - jsonrpc: "2.0", - id, - error: { - code, - message, - ...data !== void 0 && { data } - } - }).catch((error) => reportError(stdio_toError(error))); - /** - * Entry-handled `subscriptions/listen` for this connection: holds the - * active subscriptions, serves inbound listen / cancelled-of-listen - * before the pinned instance is consulted, and rewrites the instance's - * outbound change notifications onto the active subscriptions. Only - * consulted on a modern-pinned connection — on a legacy connection - * change notifications pass straight through (the 2025 unsolicited - * delivery model is unchanged). - */ - const listenRouter = new StdioListenRouter(options.maxSubscriptions ?? DEFAULT_MAX_SUBSCRIPTIONS); - /** Outbound intercept installed on a modern instance's channel. */ - const modernOutboundIntercept = (message) => { - if (!isJSONRPCNotification(message)) return void 0; - const routed = listenRouter.routeOutbound(message); - if (routed === "passthrough") return void 0; - for (const stamped of routed) wire.send({ - jsonrpc: "2.0", - ...stamped - }).catch((error) => reportError(stdio_toError(error))); - return "handled"; - }; - /** - * Entry-handled inbound listen routing for a modern-pinned connection. - * Returns `true` when the message was served at the entry and must NOT - * be delivered to the pinned instance. - */ - const tryServeListen = async (message) => { - if (isJSONRPCRequest(message) && message.method === "subscriptions/listen") { - const meta = requestMetaOf(message.params); - const issue = hasEnvelopeClaim(message.params) ? (meta === void 0 ? [] : validateEnvelopeMeta(meta))[0] : { - key: "_meta", - problem: "the per-request envelope is required on protocol revision 2026-07-28" - }; - const claimedVersion = envelopeClaimVersion(message.params); - let reply; - if (issue !== void 0) reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: -32602, - message: `Invalid _meta envelope: ${issue.key}: ${issue.problem}` - } - }; - else if (claimedVersion === void 0 || !SUPPORTED_MODERN_PROTOCOL_VERSIONS.includes(claimedVersion)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: claimedVersion ?? "unknown" - }); - reply = { - jsonrpc: "2.0", - id: message.id, - error: { - code: error.code, - message: error.message, - data: error.data - } - }; - } else reply = listenRouter.serve(message); - await wire.send("error" in reply ? reply : { - jsonrpc: "2.0", - method: reply.method, - params: reply.params - }).catch((error) => reportError(stdio_toError(error))); - return true; - } - if (isJSONRPCNotification(message) && message.method === "notifications/cancelled") { - const cancelledId = message.params?.requestId; - if (cancelledId !== void 0 && listenRouter.cancel(cancelledId)) return true; - } - return false; - }; - /** Answers a 2025-era request the entry will not serve (the modern-only rejection cells). */ - const answerLegacyRejection = (request, reason, requestedVersion) => { - const rejection = modernOnlyStrictRejection({ - kind: "legacy", - reason, - ...requestedVersion !== void 0 && { requestedVersion } - }, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - if (rejection === void 0) return Promise.resolve(); - reportError(/* @__PURE__ */ new Error(`Rejected 2025-era request on a modern-only stdio connection (${rejection.cell}): ${rejection.message}`)); - return writeErrorResponse(request.id, rejection.code, rejection.message, rejection.data); - }; - const onInstanceClosed = (channel) => { - if (closing || channel === discarding) return; - closeAll(); - }; - const connectInstance = async (era, revision) => { - const product = await factory({ era }); - const server = product instanceof McpServer ? product.server : product; - if (era === "modern") { - setNegotiatedProtocolVersion(server, revision); - installModernOnlyHandlers(server, SUPPORTED_MODERN_PROTOCOL_VERSIONS); - listenRouter.setServerCapabilities(server.getCapabilities(), serverIdentityOf(server)); - } - const channel = new StdioConnectionChannel(wire, () => onInstanceClosed(channel), era === "modern" ? modernOutboundIntercept : void 0); - await product.connect(channel); - return { - product, - channel - }; - }; - /** Closes an instance whose factory resolved only after the connection was torn down. */ - const disposeLateInstance = (instance) => instance.product.close().catch((error) => reportError(stdio_toError(error))); - const discardProbeInstance = async (instance) => { - discarding = instance.channel; - try { - if (!await instance.channel.whenRequestsAnswered(DISCARD_ANSWER_TIMEOUT_MS)) reportError(/* @__PURE__ */ new Error(`Discarded the probe instance with requests still unanswered after ${DISCARD_ANSWER_TIMEOUT_MS}ms; continuing with the fallback`)); - await instance.product.close(); - } catch (error) { - reportError(stdio_toError(error)); - } finally { - discarding = void 0; - } - }; - const processMessage = async (message) => { - if (state.phase === "closed") return; - if (state.phase === "pinned") { - if (state.era === "modern" && isJSONRPCRequest(message) && message.method === "initialize" && !carriesValidModernEnvelopeClaim(message.params)) { - await answerLegacyRejection(message, "initialize", message.params !== null && typeof message.params === "object" && typeof message.params.protocolVersion === "string" ? message.params.protocolVersion : void 0); - return; - } - if (state.era === "modern" && await tryServeListen(message)) return; - state.instance.channel.deliver(message); - return; - } - if (!isJSONRPCRequest(message) && !isJSONRPCNotification(message)) { - reportError(/* @__PURE__ */ new Error("Discarded a JSON-RPC response received before the connection negotiated an era")); - return; - } - const opening = classifyOpeningMessage(message); - switch (opening.kind) { - case "invalid-envelope": { - const detail = `Invalid _meta envelope for protocol revision 2026-07-28: ${opening.issue.key}: ${opening.issue.problem}`; - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InvalidParams, detail, { envelope: opening.issue }); - else reportError(/* @__PURE__ */ new Error(`Discarded a notification with a malformed envelope: ${detail}`)); - return; - } - case "unsupported-revision": - if (isJSONRPCRequest(message)) { - const error = new UnsupportedProtocolVersionError({ - supported: [...SUPPORTED_MODERN_PROTOCOL_VERSIONS], - requested: opening.requested - }); - reportError(error); - await writeErrorResponse(message.id, error.code, error.message, error.data); - } else reportError(/* @__PURE__ */ new Error(`Discarded a notification claiming unsupported protocol revision ${opening.requested}`)); - return; - case "modern": - if (isJSONRPCRequest(message) && message.method === "server/discover") { - if (state.phase === "probe") { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "probe", - instance - }; - instance.channel.deliver(message, { classification: opening.classification }); - return; - } - if (state.phase === "probe") { - if (isJSONRPCNotification(message)) { - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - } - state = { - phase: "pinned", - era: "modern", - instance: state.instance - }; - } else { - const instance = await connectInstance("modern", opening.revision); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "modern", - instance - }; - } - if (await tryServeListen(message)) return; - state.instance.channel.deliver(message, { classification: opening.classification }); - return; - case "legacy": { - if (legacyMode === "reject") { - if (isJSONRPCRequest(message)) await answerLegacyRejection(message, opening.reason, opening.requestedVersion); - return; - } - if (state.phase === "probe") { - await discardProbeInstance(state.instance); - if (isTornDown()) return; - state = { phase: "opening" }; - } - const instance = await connectInstance("legacy"); - if (isTornDown()) { - await disposeLateInstance(instance); - return; - } - state = { - phase: "pinned", - era: "legacy", - instance - }; - state.instance.channel.deliver(message); - return; - } - } - }; - const queue = []; - let pumping = false; - const pump = async () => { - if (pumping) return; - pumping = true; - try { - while (queue.length > 0) { - const message = queue.shift(); - try { - await processMessage(message); - } catch (error) { - if (isJSONRPCRequest(message)) await writeErrorResponse(message.id, ProtocolErrorCode.InternalError, "Internal server error"); - reportError(stdio_toError(error)); - } - } - } finally { - pumping = false; - } - }; - const closeAll = async () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - for (const result of listenRouter.teardownAll()) await wire.send(result).catch((error) => reportError(stdio_toError(error))); - if (current.phase === "probe" || current.phase === "pinned") await current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - await wire.close().catch((error) => reportError(stdio_toError(error))); - }; - wire.onmessage = (message) => { - queue.push(message); - pump(); - }; - wire.onerror = (error) => { - reportError(error); - if (state.phase === "probe" || state.phase === "pinned") state.instance.channel.onerror?.(error); - }; - wire.onclose = () => { - if (closing || state.phase === "closed") return; - closing = true; - const current = state; - state = { phase: "closed" }; - if (current.phase === "probe" || current.phase === "pinned") current.instance.product.close().catch((error) => reportError(stdio_toError(error))); - }; - const started = wire.start().catch((error) => { - reportError(stdio_toError(error)); - throw error; - }); - started.catch(() => {}); - return { close: async () => { - await started.catch(() => {}); - await closeAll(); - } }; -} -function stdio_toError(value) { - return value instanceof Error ? value : new Error(String(value)); -} - -//#endregion - -//# sourceMappingURL=stdio.mjs.map -const defaultHeartbeatIntervalMs = 300000; -const defaultActivityThrottleMs = 60000; -const defaultShutdownTimeoutMs = 5000; -const defaultHeartbeatName = 'agent-bundle'; -const redirectConsoleToStderr = ()=>{ - const originalStdoutWrite = process.stdout.write.bind(process.stdout); - const stderrConsole = new console.Console({ - stderr: process.stderr, - stdout: process.stderr - }); - const methods = [ - 'debug', - 'dir', - 'error', - 'info', - 'log', - 'trace', - 'warn' - ]; - for (const method of methods)console[method] = stderrConsole[method].bind(stderrConsole); - process.stdout.write = (chunk, encoding, callback)=>process.stderr.write(chunk, encoding, callback); - return Object.freeze({ - restoreProtocolStdout: ()=>{ - process.stdout.write = originalStdoutWrite; - } - }); -}; -const createHeartbeat = ({ activityThrottleMs = defaultActivityThrottleMs, intervalMs = defaultHeartbeatIntervalMs, name = defaultHeartbeatName, writeLine })=>{ - const startedAt = Date.now(); - let lastActivityAt = startedAt; - let lastActivityLogAt = 0; - const log = (reason)=>{ - const uptimeSeconds = Math.round((Date.now() - startedAt) / 1000); - const idleSeconds = Math.round((Date.now() - lastActivityAt) / 1000); - writeLine(`[${name}] stdio heartbeat (${reason}) pid=${process.pid} uptime=${uptimeSeconds}s idle=${idleSeconds}s`); - }; - const timer = setInterval(()=>log('interval'), intervalMs); - timer.unref?.(); - return Object.freeze({ - log, - noteActivity: ()=>{ - lastActivityAt = Date.now(); - if (lastActivityAt - lastActivityLogAt >= activityThrottleMs) { - lastActivityLogAt = lastActivityAt; - log('activity'); - } - }, - stop: ()=>clearInterval(timer) - }); -}; -const runStdioServer = async ({ activityThrottleMs, exit = (code)=>process.exit(code), heartbeat: heartbeatEnabled = true, heartbeatIntervalMs, server, serverName, shutdownTimeoutMs = defaultShutdownTimeoutMs, signals = process, stdin = process.stdin, transport, writeLine = (line)=>void process.stderr.write(`${line}\n`) })=>{ - const heartbeat = createHeartbeat({ - ...void 0 === activityThrottleMs ? {} : { - activityThrottleMs - }, - ...void 0 === heartbeatIntervalMs ? {} : { - intervalMs: heartbeatIntervalMs - }, - ...void 0 === serverName ? {} : { - name: serverName - }, - writeLine: heartbeatEnabled ? writeLine : ()=>void 0 - }); - const keepalive = setInterval(()=>void 0, 60000); - keepalive.unref?.(); - let shuttingDown = false; - const shutdown = async (exitCode = 0)=>{ - if (shuttingDown) return; - shuttingDown = true; - signals.off('SIGINT', handleSigint); - signals.off('SIGTERM', handleSigterm); - stdin.off?.('end', handleStdinEnd); - clearInterval(keepalive); - heartbeat.stop(); - await Promise.race([ - Promise.allSettled([ - Promise.resolve().then(()=>transport.close()), - Promise.resolve().then(()=>server.close()) - ]), - new Promise((resolve)=>setTimeout(resolve, shutdownTimeoutMs)) - ]); - exit(exitCode); - }; - const handleSigint = ()=>{ - shutdown(130); - }; - const handleSigterm = ()=>{ - shutdown(143); - }; - const handleStdinEnd = ()=>{ - shutdown(0); - }; - signals.on('SIGINT', handleSigint); - signals.on('SIGTERM', handleSigterm); - stdin.once?.('end', handleStdinEnd); - transport.onclose = ()=>{ - shutdown(0); - }; - await server.connect(transport); - const originalOnMessage = transport.onmessage; - transport.onmessage = (message, extra)=>{ - heartbeat.noteActivity(); - originalOnMessage?.(message, extra); - }; - return Object.freeze({ - heartbeat, - shutdown - }); -}; -const runGeneratedStdioMcpEntry = async (options)=>{ - const guard = redirectConsoleToStderr(); - const entry = await options.loadEntry(); - const factory = entry.default; - if ('function' != typeof factory) throw new TypeError(`Generated stdio entry for MCP server ${JSON.stringify(options.serverName)} must default-export a server factory.`); - const server = await factory(); - const { StdioServerTransport } = await Promise.resolve(stdio_namespaceObject); - guard.restoreProtocolStdout(); - const transport = new StdioServerTransport(); - return runStdioServer({ - ...options.lifecycle, - server, - serverName: options.serverName, - transport: transport - }); -}; - - - -await runGeneratedStdioMcpEntry({ - loadEntry: ()=>Promise.resolve(status_namespaceObject), - serverName: "status" -}); - -export {}; diff --git a/examples/mcp-app/artifact/portable/plugin.json b/examples/mcp-app/artifact/portable/plugin.json deleted file mode 100644 index e450b6e1e..000000000 --- a/examples/mcp-app/artifact/portable/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A unified service-readiness assistant with MCP, Skills, Hooks, scripts, and evaluation.","name":"mcp-app-example","version":"1.0.0"} diff --git a/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs b/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs deleted file mode 100644 index a6f274bf6..000000000 --- a/examples/mcp-app/artifact/portable/scripts/check-service-fixture.mjs +++ /dev/null @@ -1,60 +0,0 @@ -import { readFile } from "node:fs/promises"; - - - - -const healthyCompilerStatus = Object.freeze({ - checks: Object.freeze([ - Object.freeze({ - label: 'Availability', - status: 'passing' - }), - Object.freeze({ - label: 'Build queue', - status: 'passing' - }) - ]), - service: 'compiler', - status: 'healthy', - summary: 'Compiler service is ready for release.' -}); -const isRecord = (value)=>value !== null && typeof value === 'object' && !Array.isArray(value); -const isHealthyCompilerFixture = (value)=>{ - if (!isRecord(value) || value.service !== healthyCompilerStatus.service || value.status !== healthyCompilerStatus.status || value.summary !== healthyCompilerStatus.summary || !Array.isArray(value.checks) || value.checks.length !== healthyCompilerStatus.checks.length) { - return false; - } - return healthyCompilerStatus.checks.every((expected, index)=>{ - const received = value.checks[index]; - return isRecord(received) && received.label === expected.label && received.status === expected.status; - }); -}; - - - -const fixturePath = new URL('../assets/evals/fixtures/status/result.json', import.meta.url); -/** - * `agent-bundle build` detects the `main` export and generates the process - * envelope (argv, awaiting, numeric-return exit-code adoption) around it. - */ const main = async ()=>{ - try { - const fixture = JSON.parse(await readFile(fixturePath, 'utf8')); - if (!isHealthyCompilerFixture(fixture)) { - throw new Error('compiler fixture must contain the exact healthy compiler status'); - } - process.stdout.write('Compiler fixture is healthy.\n'); - return 0; - } catch (error) { - process.stderr.write(`Unable to verify service fixture: ${error instanceof Error ? error.message : String(error)}\n`); - return 1; - } -}; - - -const check_service_fixture_entry_main = main; -if (typeof check_service_fixture_entry_main !== 'function') { - throw new TypeError('Executable entry must export a main function: ' + "/fast/projects/agent-bundle-worktrees/g1-followups/examples/mcp-app/src/scripts/check-service-fixture.ts"); -} -const code = await check_service_fixture_entry_main(process.argv.slice(2)); -if (typeof code === 'number') process.exitCode = code; - -export {}; diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md b/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md deleted file mode 100644 index 8f91a79d7..000000000 --- a/examples/mcp-app/artifact/portable/skills/service-readiness/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: service-readiness -description: Reviews service health evidence and records an auditable readiness decision. ---- -# Service readiness - -## When to use - -Use this Skill when a release, incident decision, or service handoff needs a -clear health verdict backed by named checks and current evidence. - -## Required resources - -- Apply [the service status policy](references/status-policy.md) before - classifying a healthy, degraded, or blocked result. -- Deliver the decision with [the readiness report](assets/readiness-report.md). - -## Workflow - -1. Identify the service and collect its current summary and every labelled - check. Record the command, time, result, and evidence source. -2. Classify any failing check with the status policy. A degraded service is not - release-ready until its failing check has an approved mitigation. -3. State the readiness verdict only after confirming availability and the - service-specific release threshold. -4. Complete the report with the status, checks, evidence, owner, and next - action. Do not omit a failing check from the final decision. - -## Final report requirements - -State `ready`, `degraded`, `blocked`, or `needs evidence`; reproduce the -service summary; list each labelled check and its status; identify the owner -and due date for every non-passing check; and name the next required action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md b/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md deleted file mode 100644 index 3da5d52ea..000000000 --- a/examples/mcp-app/artifact/portable/skills/service-readiness/assets/readiness-report.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service readiness report - -## Verdict - -State `ready`, `degraded`, `blocked`, or `needs evidence` and name the service. - -## Evidence - -Record the collection time, command or artifact, service summary, and source. - -## Checks - -List every labelled check with its observed status and release threshold. - -## Findings and mitigation - -For each non-passing check, record the impact, owner, mitigation, due date, -and the evidence required to clear it. - -## Next action - -Name the decision owner and the next verification or release action. diff --git a/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md b/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md deleted file mode 100644 index 7e5766172..000000000 --- a/examples/mcp-app/artifact/portable/skills/service-readiness/references/status-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Service status policy - -## Evidence standard - -Readiness evidence must identify the service, collection time, check label, -observed status, and source command or artifact. Missing or stale evidence is -not a passing check. - -## Status classification - -- **Healthy**: every required release check is passing. -- **Degraded**: availability remains sufficient, but a release threshold such - as P95 latency is failing. Record an owner and mitigation before release. -- **Blocked**: availability or a critical safety check is failing. Do not - release until new passing evidence is collected. -- **Needs evidence**: the service or any required check cannot be verified. - -## Release decision - -Issue `ready` only for a healthy service with current evidence. A degraded -service needs an explicit mitigation decision; a blocked service cannot pass; -and missing evidence requires a new check rather than an assumption. diff --git a/examples/skills-starter/artifact/agent-bundle.hooks.json b/examples/skills-starter/artifact/agent-bundle.hooks.json deleted file mode 100644 index a41e820b1..000000000 --- a/examples/skills-starter/artifact/agent-bundle.hooks.json +++ /dev/null @@ -1 +0,0 @@ -{"hooks":[]} diff --git a/examples/skills-starter/artifact/agent-bundle.manifest.json b/examples/skills-starter/artifact/agent-bundle.manifest.json deleted file mode 100644 index dd6e9fecb..000000000 --- a/examples/skills-starter/artifact/agent-bundle.manifest.json +++ /dev/null @@ -1 +0,0 @@ -{"agentSkills":{"schemaSha256":"6d06b61e423317421de2295ea1fd0c7b4491bfa36c5b7705c28616dfe76d4047","sourceRevision":"69ef37e9424c0a7ea9dd2293b559e43ec8176379","specification":"https://raw.githubusercontent.com/agentskills/agentskills/69ef37e9424c0a7ea9dd2293b559e43ec8176379/docs/specification.mdx"},"files":[{"bytes":13,"kind":"generated","path":"agent-bundle.hooks.json","sha256":"4df87c0d55ad1cbfddaadb62a690a467c4a2661d5da94697caefe9492a0e01b5","sourceInputs":["agent-bundle.config.ts"]},{"bytes":358,"kind":"generated","path":"claude/.claude-plugin/marketplace.json","sha256":"173c38e9dad7ec0bc9f48f850307206bda76817250f88ee71f8148cf84232013","sourceInputs":["agent-bundle.config.ts"]},{"bytes":187,"kind":"generated","path":"claude/.claude-plugin/plugin.json","sha256":"6c214932fd8a194629570beaf09f03b5674235b3825244e41b94ac85925a17e8","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":473,"kind":"generated","path":"claude/INSTALL.md","sha256":"05237956c42069fe4812a300076665b81926069a77eecf373c4759eb73777a94","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"claude/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"claude/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"claude/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"claude/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"claude/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"claude/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"claude/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"claude/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"claude/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"claude/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":255,"kind":"generated","path":"codex/.agents/plugins/marketplace.json","sha256":"92a763708bcf83d61e127c6cb01b53004d73ba77e976b18c0be957d26ec4041e","sourceInputs":["agent-bundle.config.ts"]},{"bytes":611,"kind":"generated","path":"codex/.codex-plugin/plugin.json","sha256":"d1e15bed8bff1408dd3b254473067c0411862584b358eef88ebcbd3cd59472bc","sourceInputs":["agent-bundle.config.ts","src/skills/dependency-upgrade/SKILL.md","src/skills/incident-triage/SKILL.md","src/skills/release-review/SKILL.md"]},{"bytes":361,"kind":"generated","path":"codex/INSTALL.md","sha256":"f67365c3cd57f48d62a2f182fb250b5cd334206100a4cc643e8bdf81a1f1dfe2","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"codex/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"codex/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"codex/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"codex/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"codex/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"codex/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"codex/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"codex/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"codex/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"codex/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]},{"bytes":704,"kind":"generated","path":"portable/INSTALL.md","sha256":"36fcad70168df8ba84710412655ff3baf636f8228357e31f3f4f22aeea4e2ef4","sourceInputs":["agent-bundle.config.ts"]},{"bytes":3308,"kind":"generated","path":"portable/install.mjs","sha256":"86a297294bf7f79001860d0d2bdd496d7bccf16a94201456f97926c3a8c3eff0","sourceInputs":["agent-bundle.config.ts"]},{"bytes":223,"kind":"generated","path":"portable/plugin.json","sha256":"bf4244be5133884977cdf0b957194f7eae0a0058abeda47916200ffd6c1a303d","sourceInputs":["agent-bundle.config.ts"]},{"bytes":481,"kind":"copy","path":"portable/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff","sourceInputs":["src/skills/dependency-upgrade/assets/upgrade-plan.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":516,"kind":"copy","path":"portable/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb","sourceInputs":["src/skills/dependency-upgrade/references/compatibility-checklist.md","src/skills/dependency-upgrade/SKILL.md"]},{"bytes":1351,"kind":"copy","path":"portable/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69","sourceInputs":["src/skills/dependency-upgrade/SKILL.md"]},{"bytes":417,"kind":"copy","path":"portable/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce","sourceInputs":["src/skills/incident-triage/assets/incident-update.md","src/skills/incident-triage/SKILL.md"]},{"bytes":461,"kind":"copy","path":"portable/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea","sourceInputs":["src/skills/incident-triage/references/triage-runbook.md","src/skills/incident-triage/SKILL.md"]},{"bytes":1399,"kind":"copy","path":"portable/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7","sourceInputs":["src/skills/incident-triage/SKILL.md"]},{"bytes":484,"kind":"copy","path":"portable/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88","sourceInputs":["src/skills/release-review/assets/report-template.md","src/skills/release-review/SKILL.md"]},{"bytes":421,"kind":"copy","path":"portable/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6","sourceInputs":["src/skills/release-review/references/checklist.md","src/skills/release-review/SKILL.md"]},{"bytes":908,"kind":"copy","path":"portable/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88","sourceInputs":["src/skills/release-review/references/release-policy.md","src/skills/release-review/SKILL.md"]},{"bytes":1353,"kind":"copy","path":"portable/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659","sourceInputs":["src/skills/release-review/SKILL.md"]}],"producer":{"name":"agent-bundle","version":"0.1.0"},"project":{"configDigest":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a","configPath":"agent-bundle.config.ts","modelDigest":"2c1281c98b2a03bbb8d8584df134d7acce0047f52a3f7abbad5b7239577cbc7a","packageName":"@agent-bundle-example/skills-starter","revision":"efe0374fe3133180d89726cb4f815e148717e618e2d08f57cdef9cb4b0d5387e","sourceInputs":[{"executable":false,"path":"agent-bundle.config.ts","sha256":"0f589d1a9536e55632bad273cce4d1b41007531a2e6868df0a687ae1a5b0893a"},{"executable":false,"path":"evals/engineering-operations.eval.ts","sha256":"60882b3746d4cd258d66d579757935f39666a6e610e86a3dbf7858807a516d69"},{"executable":false,"path":"evals/fixtures/incident/result.json","sha256":"57431bcbff2673ff2cf95f1a1dbccd063b2293b8be8bbc47b235d46f0686659d"},{"executable":false,"path":"evals/fixtures/release/result.json","sha256":"c2a2ddd2207fe2f6da264310c508d1d0384abf76d49ad796fbefcc10eb336905"},{"executable":false,"path":"evals/fixtures/upgrade/result.json","sha256":"9442378ddea4c0880d7a920ee575ed4d06cddae4b305ec403e5d95d03a4a6021"},{"executable":false,"path":"evals/graders/operations-result.ts","sha256":"476c2ca6d8937b8240384af2de0cb2036fc1a72d7cbf715f33142a6427d34471"},{"executable":false,"path":"evals/graders/release-result.ts","sha256":"c9cfcc05e760c5d672685a0a79ccbf96f532674d3e044fbce78328413f0ae06b"},{"executable":false,"path":"evals/release-readiness.eval.ts","sha256":"aa76a5bd2a0c88c0a66952d273cf8c3dd6858598eeea38853123b7b853b1fe1b"},{"executable":false,"path":"package.json","sha256":"2ad66bb88761179c61d171f49cfedec417bdb8c552201772737e54105297cdfb"},{"executable":false,"path":"README.md","sha256":"99f3588b978f59fd41971fd15911426da8d1cdff98fa531bb1f6c1e80b23c744"},{"executable":false,"path":"src/skills/dependency-upgrade/assets/upgrade-plan.md","sha256":"0312c35a9c04a2ad83b8a4fa522c01fe0834c4b98bf75b3436ce0e89cb8aedff"},{"executable":false,"path":"src/skills/dependency-upgrade/references/compatibility-checklist.md","sha256":"47fea616913afa9e185ef9321b8c7ec7b0c4cf2b7d5c5cfad10af0e9c112d3fb"},{"executable":false,"path":"src/skills/dependency-upgrade/SKILL.md","sha256":"3528992c76717319c27b32624a3e5ff3d84c61cc35a28bbf297d77819148cf69"},{"executable":false,"path":"src/skills/incident-triage/assets/incident-update.md","sha256":"97b690d6d343ca85c09027cce90482416c69447b9cbfcc76120fefb05ed3e1ce"},{"executable":false,"path":"src/skills/incident-triage/references/triage-runbook.md","sha256":"f9be7c2010d5244e8ed3a00e5df552d52553ea265014c5f3b91f3538922301ea"},{"executable":false,"path":"src/skills/incident-triage/SKILL.md","sha256":"255e814c4e04f250d3c0cb7109609baf7be3dceff46ce7584dfdf341f02fa2a7"},{"executable":false,"path":"src/skills/release-review/assets/report-template.md","sha256":"ecb13a7c6a895ec2665035897f32fdec468997a5fa442368e16309683108cf88"},{"executable":false,"path":"src/skills/release-review/references/checklist.md","sha256":"5ee81fae771e1baef7ef4a11c4abad2d7a06fd29b50aeaab3d09a6189cef13f6"},{"executable":false,"path":"src/skills/release-review/references/release-policy.md","sha256":"50c91759e4c3144e3966e4e599e25aaf291fb6a02515a9639bde189e578bac88"},{"executable":false,"path":"src/skills/release-review/SKILL.md","sha256":"d9875fcc1cb9119e8cc9c4e09abf8b31bd011bcf5f77d492aae23fbc6e9e1659"}]},"runtime":{"node":"22.12.0"},"targets":[{"adapterRevision":"1.22.0","name":"claude","observedVersion":"2.1.250","schemas":[{"name":"hooks","revision":"2.1.250","sha256":"3c6f3e4391f3dca939d75bd0b200ea88e68db939a2cb885d46f0b143293efb84"},{"name":"lsp","revision":"2.1.250","sha256":"c81fd2f57c410f70f8e5c3f84483f5ec1b575ee02802b424977826f757dccd8e"},{"name":"marketplace","revision":"2.1.250","sha256":"4ffa94e8024966e8080b9d3b338c9612bdfa255802a8491b43f74f90427bc988"},{"name":"mcp","revision":"2.1.250","sha256":"76ccf02c7bfe2d57945ba18e84da8d655529bd68b4d692f72bce28238c99067e"},{"name":"monitors","revision":"2.1.250","sha256":"d45abdf7561e4316ba217ce9c2ac84f32e1049622b74abb081693b479a54b48d"},{"name":"plugin","revision":"2.1.250","sha256":"3c9943237da86fd08ae82f698cde36dbef2ecf742098c6961cedf481fe435c12"},{"name":"settings","revision":"2.1.250","sha256":"9e86d8c5e4053e8de0e468d349e2c3dde5834d22d6769372b88570e301700073"},{"name":"theme","revision":"2.1.250","sha256":"721aa9b0bc7c60cd9359343e5c7205ffbdfea82da312f601720c9dfaa2d8cf0d"}]},{"adapterRevision":"1.7.0","name":"codex","observedVersion":"0.147.0","schemas":[{"name":"app","revision":"0.147.0","sha256":"01c720a645e437bf0c4f8c26fd4cb5a13988e5649e4a8562ee23a1d4b7355c6a"},{"name":"hooks","revision":"0.147.0","sha256":"175b859eb8e85bd287d85ee840d97c3f5c2d0dda3223507a796d158e3770eeba"},{"name":"marketplace","revision":"0.147.0","sha256":"1d43c5ed19de401fb7455c5912e4c21113f6e387aef4c28d2eca121f7554c4e8"},{"name":"mcp","revision":"0.147.0","sha256":"75bd50f9fcb85c2e8d43bc132d61c172a02f28ea8bb77389816ae77b14a4257e"},{"name":"plugin","revision":"0.147.0","sha256":"986bcafa6ef46f9dc4558f05781f53400b3d75533a075068184ba8d43670d4ec"}]},{"adapterRevision":"1.5.0","name":"portable","observedVersion":"1.0.0","schemas":[{"name":"mcp","revision":"1.0.0","sha256":"6539175bfcdf43085855183e86da40ea94b166547a72b47ae9a0a390516d3acb"},{"name":"plugin","revision":"1.0.0","sha256":"0a4aad95ce337878ad38802ebf0daa3fde76abe3f65400c86bcbb1ec0b3ab883"}]}],"validation":{"artifact":{"status":"passed"},"source":{"status":"passed"},"targets":[{"name":"claude","status":"passed"},{"name":"codex","status":"passed"},{"name":"portable","status":"passed"}]}} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json b/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json deleted file mode 100644 index 24cb4579e..000000000 --- a/examples/skills-starter/artifact/claude/.claude-plugin/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter-marketplace","owner":{"name":"skills-starter"},"plugins":[{"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","source":"./","version":"1.0.0"}]} diff --git a/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json b/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json deleted file mode 100644 index 0ef4b4869..000000000 --- a/examples/skills-starter/artifact/claude/.claude-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/claude/INSTALL.md b/examples/skills-starter/artifact/claude/INSTALL.md deleted file mode 100644 index e5e449b39..000000000 --- a/examples/skills-starter/artifact/claude/INSTALL.md +++ /dev/null @@ -1,18 +0,0 @@ -# Install skills-starter - -A practical engineering operations bundle for incidents, dependency upgrades, and releases. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Claude Code - -Claude Code installs this bundle through its local marketplace contract: - -```sh -claude plugin marketplace add ./ -claude plugin install skills-starter@skills-starter-marketplace --scope user -``` - -Replace `user` with `project` or `local` when that Claude scope is intended. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md deleted file mode 100644 index 5f91ab96e..000000000 --- a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: dependency-upgrade -description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. ---- -# Dependency upgrade - -## When to use - -Use this Skill for a library, runtime, toolchain, or platform upgrade that can -change public APIs, generated output, operational behavior, or support policy. - -## Required resources - -- Apply [the compatibility checklist](references/compatibility-checklist.md). -- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). - -## Workflow - -1. Record the current and proposed versions, why the change is needed, and the - supported runtime/package-manager matrix. -2. Read primary release notes and migration guides. List removed APIs, default - changes, peer requirements, and known regressions that intersect this repo. -3. Map affected imports, configuration, generated artifacts, consumers, and - CI/release surfaces before editing. -4. Implement the smallest coherent increment and run focused contract tests, - type checks, production builds, and packed-consumer checks. -5. Define rollout signals and a tested rollback path. Do not call the upgrade - complete until shipped output and a real consumer both pass. - -## Final answer - -State the compatibility decision, changed surfaces, evidence run, remaining -risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md deleted file mode 100644 index 15ed88f24..000000000 --- a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/assets/upgrade-plan.md +++ /dev/null @@ -1,21 +0,0 @@ -# Dependency upgrade plan - -## Decision - -Current version, target version, motivation, and compatibility verdict. - -## Affected surfaces - -Imports, configuration, generated output, consumers, CI, and release tooling. - -## Implementation increments - -Each increment, its tests, and its reversible boundary. - -## Verification - -Commands, observed results, and packed or browser consumer evidence. - -## Rollout and rollback - -Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md deleted file mode 100644 index 51ac5226a..000000000 --- a/examples/skills-starter/artifact/claude/skills/dependency-upgrade/references/compatibility-checklist.md +++ /dev/null @@ -1,9 +0,0 @@ -# Compatibility checklist - -- Runtime and package-manager support matrix is explicit. -- Direct, peer, optional, and transitive dependency effects are understood. -- Configuration defaults and removed/deprecated APIs are accounted for. -- Generated files and package exports remain deterministic. -- Type checks, focused tests, production builds, and packed consumers pass. -- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. -- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md deleted file mode 100644 index e91f53773..000000000 --- a/examples/skills-starter/artifact/claude/skills/incident-triage/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: incident-triage -description: Triages production incidents with evidence-first containment and a clear operational handoff. ---- -# Incident triage - -## When to use - -Use this Skill when an alert, customer report, or operator observation suggests -an active production incident and the team needs a fast, auditable first pass. - -## Required resources - -- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. -- Record the handoff with [the incident update template](assets/incident-update.md). - -## Workflow - -1. Establish impact: affected users, services, regions, start time, and the - strongest known symptom. Separate observed facts from hypotheses. -2. Preserve evidence before changing the system: relevant request IDs, logs, - metrics, deploys, feature flags, and dependency health. -3. Choose the smallest reversible containment action. State its expected signal - and rollback condition before executing it. -4. Re-evaluate impact after containment. Escalate when severity, ownership, or - blast radius remains uncertain. -5. Produce an incident update with timeline, current impact, actions, owners, - open questions, and the next update time. - -## Guardrails - -- Never claim root cause from correlation alone. -- Never expose credentials, customer payloads, or private identifiers. -- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md deleted file mode 100644 index 1e2b7529f..000000000 --- a/examples/skills-starter/artifact/claude/skills/incident-triage/assets/incident-update.md +++ /dev/null @@ -1,9 +0,0 @@ -# Incident update - -- **Status:** investigating | identified | monitoring | resolved -- **Impact:** users, services, regions, and start time -- **Observed evidence:** metrics, logs, requests, and recent changes -- **Actions taken:** action, owner, result, and rollback state -- **Current hypothesis:** clearly marked as confirmed or unconfirmed -- **Next steps:** owner and expected completion -- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md deleted file mode 100644 index d98d8a283..000000000 --- a/examples/skills-starter/artifact/claude/skills/incident-triage/references/triage-runbook.md +++ /dev/null @@ -1,9 +0,0 @@ -# First 30 minutes - -1. Acknowledge the incident and name an incident lead. -2. Capture the first known bad time and a comparable known-good baseline. -3. Check recent deploys, configuration changes, dependency status, and capacity. -4. Identify one measurable containment hypothesis and its rollback signal. -5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. - -Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md b/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md deleted file mode 100644 index 085376189..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: release-review -description: Reviews release evidence and issues an auditable readiness verdict. ---- -# Release review - -## When to use - -Use this Skill when a release candidate needs a go/no-go verdict supported by -checked, reproducible evidence. - -## Required resources - -- Read [the release checklist](references/checklist.md) to inspect the artifact. -- Apply [the release readiness policy](references/release-policy.md) to classify findings. -- Deliver the result with [the release readiness report template](assets/report-template.md). - -## Workflow - -1. Gather evidence for each checklist item. Cite the command, artifact path, - observed result, and reproduction steps for every finding. -2. Classify each finding using the policy severity. A blocker prevents a - `ready` verdict; unresolved non-blockers must still be disclosed. -3. Decide the verdict only after all required evidence is recorded. Use - `ready` only when there are no blockers. -4. Complete every section of the report template: verdict, evidence, findings, - blockers, and required follow-up. - -## Final report requirements - -The final report must state `ready`, `not ready`, or `needs evidence`; list -all evidence reviewed; give each finding a severity and reproduction; and make -the blocker count explicit. Do not issue `ready` when evidence is missing or a -blocker remains. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md deleted file mode 100644 index 76fb83fc7..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/assets/report-template.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness report - -## Verdict - -State `ready`, `not ready`, or `needs evidence`, and give the blocker count. - -## Evidence reviewed - -For each check, record the command, artifact path, observed result, and date. - -## Findings - -List each concrete issue, its severity, impact, owner, and reproduction. - -## Blockers - -List every unresolved blocker, or state `None`. - -## Required follow-up - -Record the owner, mitigation, and decision date for every unresolved Major or -Minor finding. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md deleted file mode 100644 index 823e865a9..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/references/checklist.md +++ /dev/null @@ -1,8 +0,0 @@ -# Release checklist - -1. Confirm the release artifact contains the documented public entrypoints. -2. Confirm generated files are reproducible from the checked-in sources. -3. Run the documented validation, build, and deterministic evaluation commands. -4. Record the command, artifact path, observed output, and reproduction for - every defect. -5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md deleted file mode 100644 index 09ceb86ba..000000000 --- a/examples/skills-starter/artifact/claude/skills/release-review/references/release-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness policy - -## Evidence standard - -Release evidence must be specific, reproducible, and tied to the candidate: -record the command, artifact path, observed result, and reproduction steps. -Missing or stale evidence is not proof of readiness. - -## Severity - -- **Blocker**: prevents safe release, violates a documented contract, or has no - viable mitigation. Any blocker requires a `not ready` verdict. -- **Major**: materially degrades a supported workflow. It must have an owner, - mitigation, and release decision recorded in the report. -- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent - `ready` when its evidence and owner are recorded. - -## Verdict policy - -Issue `ready` only when all required evidence is current and the blocker list -is empty. Issue `needs evidence` when required evidence is absent, stale, or -cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json b/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json deleted file mode 100644 index b3a1fadbc..000000000 --- a/examples/skills-starter/artifact/codex/.agents/plugins/marketplace.json +++ /dev/null @@ -1 +0,0 @@ -{"interface":{"displayName":"skills-starter"},"name":"skills-starter-marketplace","plugins":[{"category":"Productivity","name":"skills-starter","policy":{"authentication":"ON_INSTALL","installation":"AVAILABLE"},"source":{"path":"./","source":"local"}}]} diff --git a/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json b/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json deleted file mode 100644 index 44161e85b..000000000 --- a/examples/skills-starter/artifact/codex/.codex-plugin/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"author":{"name":"skills-starter"},"description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","interface":{"capabilities":["skills"],"category":"Productivity","defaultPrompt":["Help me use skills-starter."],"developerName":"skills-starter","displayName":"skills-starter","longDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","shortDescription":"A practical engineering operations bundle for incidents, dependency upgrades, and releases."},"name":"skills-starter","skills":"./skills/","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/codex/INSTALL.md b/examples/skills-starter/artifact/codex/INSTALL.md deleted file mode 100644 index 0c56ee69d..000000000 --- a/examples/skills-starter/artifact/codex/INSTALL.md +++ /dev/null @@ -1,16 +0,0 @@ -# Install skills-starter - -A practical engineering operations bundle for incidents, dependency upgrades, and releases. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Codex - -Codex installs this bundle from its local marketplace snapshot: - -```sh -codex plugin marketplace add ./ -codex plugin add skills-starter@skills-starter-marketplace -``` diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md deleted file mode 100644 index 5f91ab96e..000000000 --- a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: dependency-upgrade -description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. ---- -# Dependency upgrade - -## When to use - -Use this Skill for a library, runtime, toolchain, or platform upgrade that can -change public APIs, generated output, operational behavior, or support policy. - -## Required resources - -- Apply [the compatibility checklist](references/compatibility-checklist.md). -- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). - -## Workflow - -1. Record the current and proposed versions, why the change is needed, and the - supported runtime/package-manager matrix. -2. Read primary release notes and migration guides. List removed APIs, default - changes, peer requirements, and known regressions that intersect this repo. -3. Map affected imports, configuration, generated artifacts, consumers, and - CI/release surfaces before editing. -4. Implement the smallest coherent increment and run focused contract tests, - type checks, production builds, and packed-consumer checks. -5. Define rollout signals and a tested rollback path. Do not call the upgrade - complete until shipped output and a real consumer both pass. - -## Final answer - -State the compatibility decision, changed surfaces, evidence run, remaining -risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md deleted file mode 100644 index 15ed88f24..000000000 --- a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/assets/upgrade-plan.md +++ /dev/null @@ -1,21 +0,0 @@ -# Dependency upgrade plan - -## Decision - -Current version, target version, motivation, and compatibility verdict. - -## Affected surfaces - -Imports, configuration, generated output, consumers, CI, and release tooling. - -## Implementation increments - -Each increment, its tests, and its reversible boundary. - -## Verification - -Commands, observed results, and packed or browser consumer evidence. - -## Rollout and rollback - -Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md deleted file mode 100644 index 51ac5226a..000000000 --- a/examples/skills-starter/artifact/codex/skills/dependency-upgrade/references/compatibility-checklist.md +++ /dev/null @@ -1,9 +0,0 @@ -# Compatibility checklist - -- Runtime and package-manager support matrix is explicit. -- Direct, peer, optional, and transitive dependency effects are understood. -- Configuration defaults and removed/deprecated APIs are accounted for. -- Generated files and package exports remain deterministic. -- Type checks, focused tests, production builds, and packed consumers pass. -- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. -- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md deleted file mode 100644 index e91f53773..000000000 --- a/examples/skills-starter/artifact/codex/skills/incident-triage/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: incident-triage -description: Triages production incidents with evidence-first containment and a clear operational handoff. ---- -# Incident triage - -## When to use - -Use this Skill when an alert, customer report, or operator observation suggests -an active production incident and the team needs a fast, auditable first pass. - -## Required resources - -- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. -- Record the handoff with [the incident update template](assets/incident-update.md). - -## Workflow - -1. Establish impact: affected users, services, regions, start time, and the - strongest known symptom. Separate observed facts from hypotheses. -2. Preserve evidence before changing the system: relevant request IDs, logs, - metrics, deploys, feature flags, and dependency health. -3. Choose the smallest reversible containment action. State its expected signal - and rollback condition before executing it. -4. Re-evaluate impact after containment. Escalate when severity, ownership, or - blast radius remains uncertain. -5. Produce an incident update with timeline, current impact, actions, owners, - open questions, and the next update time. - -## Guardrails - -- Never claim root cause from correlation alone. -- Never expose credentials, customer payloads, or private identifiers. -- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md deleted file mode 100644 index 1e2b7529f..000000000 --- a/examples/skills-starter/artifact/codex/skills/incident-triage/assets/incident-update.md +++ /dev/null @@ -1,9 +0,0 @@ -# Incident update - -- **Status:** investigating | identified | monitoring | resolved -- **Impact:** users, services, regions, and start time -- **Observed evidence:** metrics, logs, requests, and recent changes -- **Actions taken:** action, owner, result, and rollback state -- **Current hypothesis:** clearly marked as confirmed or unconfirmed -- **Next steps:** owner and expected completion -- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md deleted file mode 100644 index d98d8a283..000000000 --- a/examples/skills-starter/artifact/codex/skills/incident-triage/references/triage-runbook.md +++ /dev/null @@ -1,9 +0,0 @@ -# First 30 minutes - -1. Acknowledge the incident and name an incident lead. -2. Capture the first known bad time and a comparable known-good baseline. -3. Check recent deploys, configuration changes, dependency status, and capacity. -4. Identify one measurable containment hypothesis and its rollback signal. -5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. - -Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md b/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md deleted file mode 100644 index 085376189..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: release-review -description: Reviews release evidence and issues an auditable readiness verdict. ---- -# Release review - -## When to use - -Use this Skill when a release candidate needs a go/no-go verdict supported by -checked, reproducible evidence. - -## Required resources - -- Read [the release checklist](references/checklist.md) to inspect the artifact. -- Apply [the release readiness policy](references/release-policy.md) to classify findings. -- Deliver the result with [the release readiness report template](assets/report-template.md). - -## Workflow - -1. Gather evidence for each checklist item. Cite the command, artifact path, - observed result, and reproduction steps for every finding. -2. Classify each finding using the policy severity. A blocker prevents a - `ready` verdict; unresolved non-blockers must still be disclosed. -3. Decide the verdict only after all required evidence is recorded. Use - `ready` only when there are no blockers. -4. Complete every section of the report template: verdict, evidence, findings, - blockers, and required follow-up. - -## Final report requirements - -The final report must state `ready`, `not ready`, or `needs evidence`; list -all evidence reviewed; give each finding a severity and reproduction; and make -the blocker count explicit. Do not issue `ready` when evidence is missing or a -blocker remains. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md deleted file mode 100644 index 76fb83fc7..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/assets/report-template.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness report - -## Verdict - -State `ready`, `not ready`, or `needs evidence`, and give the blocker count. - -## Evidence reviewed - -For each check, record the command, artifact path, observed result, and date. - -## Findings - -List each concrete issue, its severity, impact, owner, and reproduction. - -## Blockers - -List every unresolved blocker, or state `None`. - -## Required follow-up - -Record the owner, mitigation, and decision date for every unresolved Major or -Minor finding. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md deleted file mode 100644 index 823e865a9..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/references/checklist.md +++ /dev/null @@ -1,8 +0,0 @@ -# Release checklist - -1. Confirm the release artifact contains the documented public entrypoints. -2. Confirm generated files are reproducible from the checked-in sources. -3. Run the documented validation, build, and deterministic evaluation commands. -4. Record the command, artifact path, observed output, and reproduction for - every defect. -5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md deleted file mode 100644 index 09ceb86ba..000000000 --- a/examples/skills-starter/artifact/codex/skills/release-review/references/release-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness policy - -## Evidence standard - -Release evidence must be specific, reproducible, and tied to the candidate: -record the command, artifact path, observed result, and reproduction steps. -Missing or stale evidence is not proof of readiness. - -## Severity - -- **Blocker**: prevents safe release, violates a documented contract, or has no - viable mitigation. Any blocker requires a `not ready` verdict. -- **Major**: materially degrades a supported workflow. It must have an owner, - mitigation, and release decision recorded in the report. -- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent - `ready` when its evidence and owner are recorded. - -## Verdict policy - -Issue `ready` only when all required evidence is current and the blocker list -is empty. Issue `needs evidence` when required evidence is absent, stale, or -cannot be reproduced. Otherwise issue `not ready`. diff --git a/examples/skills-starter/artifact/portable/INSTALL.md b/examples/skills-starter/artifact/portable/INSTALL.md deleted file mode 100644 index bf452980c..000000000 --- a/examples/skills-starter/artifact/portable/INSTALL.md +++ /dev/null @@ -1,19 +0,0 @@ -# Install skills-starter - -A practical engineering operations bundle for incidents, dependency upgrades, and releases. - -Version: `1.0.0` - -Run these commands from this bundle directory. - -## Portable Agent Plugin - -Portable is a distribution profile, not a host runtime with one universal install location. -This bundle follows the Agent Plugins open standard (Agent Plugins 1.0.0, https://agent-plugins.org). -Cursor loads this format natively from `~/.cursor/plugins/local/`; restart Cursor or run -`Developer: Reload Window` after copying it. Codex, VS Code, GitHub Copilot, Kiro, and ChatGPT -are also native clients. The bundled installer provides the Cursor local copy: - -```sh -node ./install.mjs -``` diff --git a/examples/skills-starter/artifact/portable/install.mjs b/examples/skills-starter/artifact/portable/install.mjs deleted file mode 100644 index 51b9b39a7..000000000 --- a/examples/skills-starter/artifact/portable/install.mjs +++ /dev/null @@ -1,80 +0,0 @@ -#!/usr/bin/env node -import { createHash } from 'node:crypto'; -import { cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm } from 'node:fs/promises'; -import { homedir } from 'node:os'; -import { basename, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -const pluginName = "skills-starter"; -const pluginVersion = "1.0.0"; -const source = resolve(fileURLToPath(new URL('.', import.meta.url))); -const cursorRoot = join(homedir(), '.cursor'); -const installRoot = join(cursorRoot, 'plugins', 'local'); -const destination = join(installRoot, pluginName); - -const exists = async (path) => { - try { await lstat(path); return true; } - catch (error) { if (error?.code === 'ENOENT') return false; throw error; } -}; - -const treeHash = async (root, prefix = '') => { - const rootMetadata = await lstat(root); - if (rootMetadata.isSymbolicLink() || !rootMetadata.isDirectory()) { - throw new Error('Refusing unsupported filesystem entry ".".'); - } - const hash = createHash('sha256'); - const visit = async (relative) => { - const absolute = join(root, relative); - const metadata = await lstat(absolute); - if (metadata.isSymbolicLink() || (!metadata.isDirectory() && !metadata.isFile())) { - throw new Error(`Refusing unsupported filesystem entry ${JSON.stringify(relative || '.')}.`); - } - if (metadata.isDirectory()) { - for (const name of (await readdir(absolute)).sort()) await visit(join(relative, name)); - return; - } - hash.update(relative.replaceAll('\\', '/')); - hash.update('\0'); - hash.update(await readFile(absolute)); - hash.update('\0'); - }; - for (const name of (await readdir(root)).sort()) await visit(join(prefix, name)); - return hash.digest('hex'); -}; - -const installedVersion = async () => { - for (const manifest of ['.cursor-plugin/plugin.json', 'plugin.json']) { - try { - const value = JSON.parse(await readFile(join(destination, manifest), 'utf8')); - if (typeof value.version === 'string') return value.version; - } catch (error) { if (error?.code !== 'ENOENT') throw error; } - } - return undefined; -}; - -if (!(await exists(cursorRoot)) || !(await lstat(cursorRoot)).isDirectory()) { - throw new Error(`Cursor is not installed in ${cursorRoot}.`); -} -await mkdir(installRoot, { recursive: true }); -if (await exists(destination)) { - const currentVersion = await installedVersion(); - if (currentVersion !== undefined && currentVersion !== pluginVersion) { - throw new Error(`Refusing version collision at ${destination}: found ${currentVersion}, requested ${pluginVersion}.`); - } - if (source === destination || await treeHash(source) === await treeHash(destination)) { - console.log(`Already installed ${pluginName}@${pluginVersion} at ${destination}`); - process.exit(0); - } - throw new Error(`Refusing content collision at ${destination}.`); -} - -const stageParent = await mkdtemp(join(installRoot, `.${basename(destination)}.stage-`)); -const stage = join(stageParent, 'bundle'); -try { - await cp(source, stage, { errorOnExist: true, force: false, recursive: true, verbatimSymlinks: true }); - await treeHash(stage); - await rename(stage, destination); - console.log(`Installed ${pluginName}@${pluginVersion} at ${destination}`); -} finally { - await rm(stageParent, { force: true, recursive: true }); -} diff --git a/examples/skills-starter/artifact/portable/plugin.json b/examples/skills-starter/artifact/portable/plugin.json deleted file mode 100644 index 42585f082..000000000 --- a/examples/skills-starter/artifact/portable/plugin.json +++ /dev/null @@ -1 +0,0 @@ -{"$schema":"https://agent-plugins.org/schemas/1.0.0/plugin.schema.json","description":"A practical engineering operations bundle for incidents, dependency upgrades, and releases.","name":"skills-starter","version":"1.0.0"} diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md deleted file mode 100644 index 5f91ab96e..000000000 --- a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/SKILL.md +++ /dev/null @@ -1,33 +0,0 @@ ---- -name: dependency-upgrade -description: Plans and verifies dependency upgrades with compatibility, rollout, and rollback evidence. ---- -# Dependency upgrade - -## When to use - -Use this Skill for a library, runtime, toolchain, or platform upgrade that can -change public APIs, generated output, operational behavior, or support policy. - -## Required resources - -- Apply [the compatibility checklist](references/compatibility-checklist.md). -- Write the proposal with [the upgrade plan template](assets/upgrade-plan.md). - -## Workflow - -1. Record the current and proposed versions, why the change is needed, and the - supported runtime/package-manager matrix. -2. Read primary release notes and migration guides. List removed APIs, default - changes, peer requirements, and known regressions that intersect this repo. -3. Map affected imports, configuration, generated artifacts, consumers, and - CI/release surfaces before editing. -4. Implement the smallest coherent increment and run focused contract tests, - type checks, production builds, and packed-consumer checks. -5. Define rollout signals and a tested rollback path. Do not call the upgrade - complete until shipped output and a real consumer both pass. - -## Final answer - -State the compatibility decision, changed surfaces, evidence run, remaining -risk, rollout signal, and exact rollback trigger. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md deleted file mode 100644 index 15ed88f24..000000000 --- a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/assets/upgrade-plan.md +++ /dev/null @@ -1,21 +0,0 @@ -# Dependency upgrade plan - -## Decision - -Current version, target version, motivation, and compatibility verdict. - -## Affected surfaces - -Imports, configuration, generated output, consumers, CI, and release tooling. - -## Implementation increments - -Each increment, its tests, and its reversible boundary. - -## Verification - -Commands, observed results, and packed or browser consumer evidence. - -## Rollout and rollback - -Owner, monitored signals, rollback trigger, and rollback procedure. diff --git a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md b/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md deleted file mode 100644 index 51ac5226a..000000000 --- a/examples/skills-starter/artifact/portable/skills/dependency-upgrade/references/compatibility-checklist.md +++ /dev/null @@ -1,9 +0,0 @@ -# Compatibility checklist - -- Runtime and package-manager support matrix is explicit. -- Direct, peer, optional, and transitive dependency effects are understood. -- Configuration defaults and removed/deprecated APIs are accounted for. -- Generated files and package exports remain deterministic. -- Type checks, focused tests, production builds, and packed consumers pass. -- CI caches, lockfiles, SBOM, license, and provenance checks remain valid. -- Rollout ownership, telemetry, and rollback conditions are documented. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md b/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md deleted file mode 100644 index e91f53773..000000000 --- a/examples/skills-starter/artifact/portable/skills/incident-triage/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: incident-triage -description: Triages production incidents with evidence-first containment and a clear operational handoff. ---- -# Incident triage - -## When to use - -Use this Skill when an alert, customer report, or operator observation suggests -an active production incident and the team needs a fast, auditable first pass. - -## Required resources - -- Follow [the triage runbook](references/triage-runbook.md) for the first 30 minutes. -- Record the handoff with [the incident update template](assets/incident-update.md). - -## Workflow - -1. Establish impact: affected users, services, regions, start time, and the - strongest known symptom. Separate observed facts from hypotheses. -2. Preserve evidence before changing the system: relevant request IDs, logs, - metrics, deploys, feature flags, and dependency health. -3. Choose the smallest reversible containment action. State its expected signal - and rollback condition before executing it. -4. Re-evaluate impact after containment. Escalate when severity, ownership, or - blast radius remains uncertain. -5. Produce an incident update with timeline, current impact, actions, owners, - open questions, and the next update time. - -## Guardrails - -- Never claim root cause from correlation alone. -- Never expose credentials, customer payloads, or private identifiers. -- Never make a destructive or irreversible change without explicit authority. diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md b/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md deleted file mode 100644 index 1e2b7529f..000000000 --- a/examples/skills-starter/artifact/portable/skills/incident-triage/assets/incident-update.md +++ /dev/null @@ -1,9 +0,0 @@ -# Incident update - -- **Status:** investigating | identified | monitoring | resolved -- **Impact:** users, services, regions, and start time -- **Observed evidence:** metrics, logs, requests, and recent changes -- **Actions taken:** action, owner, result, and rollback state -- **Current hypothesis:** clearly marked as confirmed or unconfirmed -- **Next steps:** owner and expected completion -- **Next update:** timestamp diff --git a/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md b/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md deleted file mode 100644 index d98d8a283..000000000 --- a/examples/skills-starter/artifact/portable/skills/incident-triage/references/triage-runbook.md +++ /dev/null @@ -1,9 +0,0 @@ -# First 30 minutes - -1. Acknowledge the incident and name an incident lead. -2. Capture the first known bad time and a comparable known-good baseline. -3. Check recent deploys, configuration changes, dependency status, and capacity. -4. Identify one measurable containment hypothesis and its rollback signal. -5. Update stakeholders with facts, uncertainty, owners, and the next checkpoint. - -Severity is driven by user impact and recovery risk, not by alert volume. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md b/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md deleted file mode 100644 index 085376189..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/SKILL.md +++ /dev/null @@ -1,34 +0,0 @@ ---- -name: release-review -description: Reviews release evidence and issues an auditable readiness verdict. ---- -# Release review - -## When to use - -Use this Skill when a release candidate needs a go/no-go verdict supported by -checked, reproducible evidence. - -## Required resources - -- Read [the release checklist](references/checklist.md) to inspect the artifact. -- Apply [the release readiness policy](references/release-policy.md) to classify findings. -- Deliver the result with [the release readiness report template](assets/report-template.md). - -## Workflow - -1. Gather evidence for each checklist item. Cite the command, artifact path, - observed result, and reproduction steps for every finding. -2. Classify each finding using the policy severity. A blocker prevents a - `ready` verdict; unresolved non-blockers must still be disclosed. -3. Decide the verdict only after all required evidence is recorded. Use - `ready` only when there are no blockers. -4. Complete every section of the report template: verdict, evidence, findings, - blockers, and required follow-up. - -## Final report requirements - -The final report must state `ready`, `not ready`, or `needs evidence`; list -all evidence reviewed; give each finding a severity and reproduction; and make -the blocker count explicit. Do not issue `ready` when evidence is missing or a -blocker remains. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md b/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md deleted file mode 100644 index 76fb83fc7..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/assets/report-template.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness report - -## Verdict - -State `ready`, `not ready`, or `needs evidence`, and give the blocker count. - -## Evidence reviewed - -For each check, record the command, artifact path, observed result, and date. - -## Findings - -List each concrete issue, its severity, impact, owner, and reproduction. - -## Blockers - -List every unresolved blocker, or state `None`. - -## Required follow-up - -Record the owner, mitigation, and decision date for every unresolved Major or -Minor finding. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md b/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md deleted file mode 100644 index 823e865a9..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/references/checklist.md +++ /dev/null @@ -1,8 +0,0 @@ -# Release checklist - -1. Confirm the release artifact contains the documented public entrypoints. -2. Confirm generated files are reproducible from the checked-in sources. -3. Run the documented validation, build, and deterministic evaluation commands. -4. Record the command, artifact path, observed output, and reproduction for - every defect. -5. Classify every defect with the severity from the release readiness policy. diff --git a/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md b/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md deleted file mode 100644 index 09ceb86ba..000000000 --- a/examples/skills-starter/artifact/portable/skills/release-review/references/release-policy.md +++ /dev/null @@ -1,22 +0,0 @@ -# Release readiness policy - -## Evidence standard - -Release evidence must be specific, reproducible, and tied to the candidate: -record the command, artifact path, observed result, and reproduction steps. -Missing or stale evidence is not proof of readiness. - -## Severity - -- **Blocker**: prevents safe release, violates a documented contract, or has no - viable mitigation. Any blocker requires a `not ready` verdict. -- **Major**: materially degrades a supported workflow. It must have an owner, - mitigation, and release decision recorded in the report. -- **Minor**: limited-scope issue with an agreed follow-up. It does not prevent - `ready` when its evidence and owner are recorded. - -## Verdict policy - -Issue `ready` only when all required evidence is current and the blocker list -is empty. Issue `needs evidence` when required evidence is absent, stale, or -cannot be reproduced. Otherwise issue `not ready`. diff --git a/packages/agent-bundle/tests/packed-stdio-projection.test.ts b/packages/agent-bundle/tests/packed-stdio-projection.test.ts index 4cadf0ace..74e91351a 100644 --- a/packages/agent-bundle/tests/packed-stdio-projection.test.ts +++ b/packages/agent-bundle/tests/packed-stdio-projection.test.ts @@ -126,6 +126,7 @@ it('serves compiled routes and durable state across packed process restarts', as 'publish-notice', 'strict-report', 'ticket', + 'tooling', 'unavailable', 'wait', ]); From 81e3437952a6a6ff76a1bb220c4604f7c8048345 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 07:52:07 +0000 Subject: [PATCH 07/13] fix(build): mount the compiled event route id as operationId in the Flight worker The generated worker resolved event routes by their hook identity and mounted that identity (`hook:event-route:tool-after`) as `invocation.operationId`, while the hook shell's request scope, the lifecycle replay, the test manifest, and `renderRoute` all use the compiled route id (`event:tool/after`). The worker record now carries the compiled id, so a route reading `invocation.operationId` sees one value on every surface; pinned by the warm-runtime integration test and the worker source digest. --- .changeset/test-harness-conventional-providers.md | 2 +- packages/agent-bundle/src/build/entry-shell.ts | 10 +++++++++- packages/agent-bundle/tests/entry-shell.test.ts | 8 +++++++- .../tests/generated-route-server.test.ts | 13 ++++++++----- 4 files changed, 25 insertions(+), 8 deletions(-) diff --git a/.changeset/test-harness-conventional-providers.md b/.changeset/test-harness-conventional-providers.md index aad845ed4..d578ce830 100644 --- a/.changeset/test-harness-conventional-providers.md +++ b/.changeset/test-harness-conventional-providers.md @@ -2,4 +2,4 @@ "agent-bundle": patch --- -The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity. Passing `context.providers` opts out and mounts the explicit map verbatim. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. +The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity. Passing `context.providers` opts out and mounts the explicit map verbatim. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id, and the generated Flight worker now mounts an event route's compiled id (`event:tool/after`) as `invocation.operationId`, matching the hook shell's request scope, the lifecycle replay, and the harness instead of the internal hook identity. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. diff --git a/packages/agent-bundle/src/build/entry-shell.ts b/packages/agent-bundle/src/build/entry-shell.ts index ba05e3a73..5ad3e58ba 100644 --- a/packages/agent-bundle/src/build/entry-shell.ts +++ b/packages/agent-bundle/src/build/entry-shell.ts @@ -555,11 +555,19 @@ const eventRouteImports = ( ): readonly string[] => routes.map((route, index) => `import * as route${String(offset + index)} from ${JSON.stringify(route.source)};`); +/** + * Event route records stay keyed by the hook identity the worker resolves + * from the canonical event (`hook:event-route:tool-after`), but the record's + * `id` is the compiled route id (`event:tool/after`): that is the + * `operationId` the hook shell opens the request scope with, the lifecycle + * replay mounts, the test manifest addresses, and the harness renders, so a + * route reading `invocation.operationId` sees one value everywhere. + */ const eventRouteRecords = ( routes: readonly NormalizedHook[], offset: number, ): readonly string[] => routes.map((route, index) => - ` ${JSON.stringify(route.id)}: Object.freeze({ event: ${JSON.stringify(route.eventRoute!.event)}, id: ${JSON.stringify(route.id)}, kind: 'event-route', module: route${String(offset + index)}, name: ${JSON.stringify(route.eventRoute!.event)} }),`); + ` ${JSON.stringify(route.id)}: Object.freeze({ event: ${JSON.stringify(route.eventRoute!.event)}, id: ${JSON.stringify(`event:${route.eventRoute!.event}`)}, kind: 'event-route', module: route${String(offset + index)}, name: ${JSON.stringify(route.eventRoute!.event)} }),`); const providerImports = (providers: readonly CompiledProvider[]): readonly string[] => providers.map((provider, index) => diff --git a/packages/agent-bundle/tests/entry-shell.test.ts b/packages/agent-bundle/tests/entry-shell.test.ts index 9c23f5f05..16f4e3c10 100644 --- a/packages/agent-bundle/tests/entry-shell.test.ts +++ b/packages/agent-bundle/tests/entry-shell.test.ts @@ -357,8 +357,14 @@ it('generates the warm react-server Flight worker separately from the MCP dispat expect(source).toContain('/project/src/mcp/curator/tools/inspect.tsx'); expect(source).toContain('/project/src/events/tool/after.tsx'); expect(source).toContain("message.invocation.kind === 'event'"); + // The worker resolves the event route by its hook identity but mounts the + // compiled route id as `operationId`, the same id the hook shell, the + // lifecycle replay, and the test harness use for that route. + expect(source).toContain( + '"hook:event-route:tool-after": Object.freeze({ event: "tool/after", id: "event:tool/after", kind: \'event-route\'', + ); expect(createHash('sha256').update(source).digest('hex')).toBe( - '2b9feba295b3a77cd14bdee6527379837a9a21712e649c545d35d1fed107245d', + 'f0a574cc26aa4c7d5556e7468d13743c1da55d372fe5e6eae9151df0be873948', ); expect(generate({ artifactEpoch: 'route-fixture@1.2.3', diff --git a/packages/agent-bundle/tests/generated-route-server.test.ts b/packages/agent-bundle/tests/generated-route-server.test.ts index 734366eea..61c77cf78 100644 --- a/packages/agent-bundle/tests/generated-route-server.test.ts +++ b/packages/agent-bundle/tests/generated-route-server.test.ts @@ -918,7 +918,7 @@ it('renders composite plugin events through each concrete host in one warm runti ' const context = await agent();', ' const processLifetime = context.providers.processLifetime as { hits: number; instanceId: string };', ' const host = context.host.state === "available" ? context.host.value.name : "unavailable";', - ' return createElement(Agent.Result, null, createElement(Agent.Context, null, `${host}:tool/after:${String(processLifetime.hits)}:${processLifetime.instanceId}`));', + ' return createElement(Agent.Result, null, createElement(Agent.Context, null, `${host}:${context.invocation.operationId}|${context.invocation.surface}:${String(processLifetime.hits)}:${processLifetime.instanceId}`));', '}', '', ].join('\n')), @@ -973,11 +973,14 @@ it('renders composite plugin events through each concrete host in one warm runti }, { AGENT_BUNDLE_HOOK_HOST: undefined, PLUGIN_ROOT: undefined }); const firstContext = (claude as { hookSpecificOutput: { additionalContext: string } }) .hookSpecificOutput.additionalContext; - const instanceId = firstContext.slice('claude:tool/after:1:'.length); + // The worker mounts the compiled route id as `operationId` and the + // canonical event as `surface` — the same pair the hook shell, the + // lifecycle replay, and `renderRoute` record for this route. + const instanceId = firstContext.slice('claude:event:tool/after|tool/after:1:'.length); expect(instanceId).not.toBe(''); expect(claude).toEqual({ hookSpecificOutput: { - additionalContext: `claude:tool/after:1:${instanceId}`, + additionalContext: `claude:event:tool/after|tool/after:1:${instanceId}`, hookEventName: 'PostToolUse', }, }); @@ -993,7 +996,7 @@ it('renders composite plugin events through each concrete host in one warm runti transcript_path: null, }, { AGENT_BUNDLE_HOOK_HOST: undefined, PLUGIN_ROOT: output })).resolves.toEqual({ hookSpecificOutput: { - additionalContext: `codex:tool/after:2:${instanceId}`, + additionalContext: `codex:event:tool/after|tool/after:2:${instanceId}`, hookEventName: 'PostToolUse', }, }); @@ -1008,7 +1011,7 @@ it('renders composite plugin events through each concrete host in one warm runti tool_output: '{"ok":true}', tool_use_id: 'tool-cursor', }, { AGENT_BUNDLE_HOOK_HOST: undefined, PLUGIN_ROOT: undefined })).resolves.toEqual({ - additional_context: `cursor:tool/after:3:${instanceId}`, + additional_context: `cursor:event:tool/after|tool/after:3:${instanceId}`, }); await expect(runHook(sharedSession.output, { From 0cf800f0d893ecc682b1f32ab0abfce79e980c06 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 08:26:11 +0000 Subject: [PATCH 08/13] fix(test): scope the harness process lifetime to each simulated executable A module-level lifetime made unrelated invokeCli calls, renders, and MCP sessions look like one warm process, so a provider branching on hits or instanceId could pass in the harness and fail in the artifact. The lifetime now lives on the logical executable exactly as the artifact scopes it: fresh per CLI invocation and per route-unit render, shared across the requests of one open in-memory MCP server, and fresh again for the open-call-close helper. --- .../test-harness-conventional-providers.md | 2 +- packages/agent-bundle/README.md | 8 +-- .../src/mcp/harness/tools/tooling.tsx | 8 ++- packages/agent-bundle/src/test/cli.ts | 6 +++ packages/agent-bundle/src/test/mcp.ts | 5 ++ packages/agent-bundle/src/test/providers.ts | 22 ++++---- packages/agent-bundle/src/test/render.ts | 8 +++ .../tests/projection/providers.test.ts | 53 ++++++++++++++++--- 8 files changed, 90 insertions(+), 22 deletions(-) diff --git a/.changeset/test-harness-conventional-providers.md b/.changeset/test-harness-conventional-providers.md index d578ce830..f145a157e 100644 --- a/.changeset/test-harness-conventional-providers.md +++ b/.changeset/test-harness-conventional-providers.md @@ -2,4 +2,4 @@ "agent-bundle": patch --- -The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity. Passing `context.providers` opts out and mounts the explicit map verbatim. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id, and the generated Flight worker now mounts an event route's compiled id (`event:tool/after`) as `invocation.operationId`, matching the hook shell's request scope, the lifecycle replay, and the harness instead of the internal hook identity. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. +The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity scoped like the artifact's (fresh per CLI invocation and per route-unit render; shared across the requests of one open in-memory MCP server). Passing `context.providers` opts out and mounts the explicit map verbatim. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id, and the generated Flight worker now mounts an event route's compiled id (`event:tool/after`) as `invocation.operationId`, matching the hook shell's request scope, the lifecycle replay, and the harness instead of the internal hook identity. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. diff --git a/packages/agent-bundle/README.md b/packages/agent-bundle/README.md index 7ea825c27..46421d84e 100644 --- a/packages/agent-bundle/README.md +++ b/packages/agent-bundle/README.md @@ -418,9 +418,11 @@ are mounted automatically for every manifest-backed helper — `renderRoute`, generated request scopes mount them: discovered from the compiled manifest, executed once per request in the same deterministic key order, handed the same surface-specific `invocation` (`tool`, `event`, `cli`, `script`), and failing the -request closed when a factory throws. `providers.processLifetime` carries the -test worker's process identity and a per-request hit counter, like the -artifact's. Pass `context.providers` to opt out: an explicit map is mounted +request closed when a factory throws. `providers.processLifetime` is scoped the +way the artifact scopes it: each `invokeCli` call and each `renderRoute` render +is a fresh simulated executable (hit 1, new `instanceId`), while one open +`openInMemoryMcpServer` session shares a single identity across every request +it handles, like the artifact's warm Flight worker. Pass `context.providers` to opt out: an explicit map is mounted verbatim and no conventional provider runs, which is how a test stubs a provider that would otherwise reach the network or the file system. diff --git a/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx b/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx index 439aa383c..95b1d5a2c 100644 --- a/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx +++ b/packages/agent-bundle/fixtures/route-harness/src/mcp/harness/tools/tooling.tsx @@ -15,11 +15,17 @@ export const inputSchema = z.object({ export const resultSchema = z.object({ keys: z.array(z.string()), libraryTooling: z.unknown().optional(), + processLifetime: z.object({ hits: z.number(), instanceId: z.string(), pid: z.number() }).optional(), }).strict(); export default async function Tooling() { const { providers } = await agent(); - const value = { keys: Object.keys(providers).sort(), libraryTooling: providers['libraryTooling'] as JsonValue }; + const { processLifetime } = providers; + const value = { + keys: Object.keys(providers).sort(), + libraryTooling: providers['libraryTooling'] as JsonValue, + ...(processLifetime === undefined ? {} : { processLifetime: { ...processLifetime } }), + }; return ( {`tooling: ${JSON.stringify(providers['libraryTooling'])}`} diff --git a/packages/agent-bundle/src/test/cli.ts b/packages/agent-bundle/src/test/cli.ts index 39f683c16..bbcb6f980 100644 --- a/packages/agent-bundle/src/test/cli.ts +++ b/packages/agent-bundle/src/test/cli.ts @@ -21,6 +21,7 @@ import type * as AgentRuntime from '@agent-bundle/runtime'; import { CliInputError, runGeneratedCliEntry } from '../cli-entry.ts'; import type { CliRenderedEvent } from '../cli-entry.ts'; +import { createProviderProcessLifetime } from '../routes/provider-execution.ts'; import type { CompiledCliCommand } from '../routes/types.ts'; import { AgentTestError, captured } from './errors.ts'; import { CLI_DISPATCH_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; @@ -164,6 +165,9 @@ export const invokeCli = async ( const runtime = await loadRuntime(); const context = options.context ?? {}; const signal = options.signal ?? new AbortController().signal; + // One simulated executable per invocation: the generated CLI creates its + // process identity at module load, so every separate run starts at hit 1. + const processLifetime = createProviderProcessLifetime(); const renderedCommands = manifest.cliCommands.filter((command) => command.rendered); let executed: CompiledCliCommand | undefined; @@ -184,6 +188,7 @@ export const invokeCli = async ( manifest, modules: renderedModules, onValidated: (validated) => { value = validated; }, + processLifetime, provenance: { kind: 'cli', manifestDigest: manifest.digest, @@ -234,6 +239,7 @@ export const invokeCli = async ( explicit: context.providers, invocation: { kind: 'cli', props: { args: execution.args, command: commandPath(command) } }, manifest, + processLifetime, provenance: { ...provenance, kind: 'cli', routeId: command.routeId, source: 'manifest', targets: [] }, signal: execution.signal, }); diff --git a/packages/agent-bundle/src/test/mcp.ts b/packages/agent-bundle/src/test/mcp.ts index 201c0b056..7184373d7 100644 --- a/packages/agent-bundle/src/test/mcp.ts +++ b/packages/agent-bundle/src/test/mcp.ts @@ -22,6 +22,7 @@ import type { } from '@agent-bundle/runtime/state'; import type { createGeneratedRuntimeState } from '@agent-bundle/runtime/mount'; +import { createProviderProcessLifetime } from '../routes/provider-execution.ts'; import { AgentTestError, captured } from './errors.ts'; import { MCP_IN_MEMORY_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; import { mountProviders } from './providers.ts'; @@ -312,6 +313,9 @@ export const openInMemoryMcpServer = async < // the same warm host wrapper the artifact uses — it simply renders here // instead of in a spawned thread. const artifactEpoch = `${manifest.plugin.name}@${manifest.plugin.version}`; + // One process identity per open server, like the artifact's Flight worker: + // every request this session handles shares it, and a new server starts fresh. + const processLifetime = createProviderProcessLifetime(); const runtimeState = options.state === undefined ? undefined : dependencies.createGeneratedRuntimeState(options.state); @@ -338,6 +342,7 @@ export const openInMemoryMcpServer = async < explicit: context.providers, invocation: request.invocation, manifest, + processLifetime, ...(descriptor === undefined ? {} : { provenance: routeProvenance(descriptor, manifest) }), signal: request.signal, }); diff --git a/packages/agent-bundle/src/test/providers.ts b/packages/agent-bundle/src/test/providers.ts index 83be73072..82a3df852 100644 --- a/packages/agent-bundle/src/test/providers.ts +++ b/packages/agent-bundle/src/test/providers.ts @@ -1,10 +1,10 @@ import type { AgentProviderValues } from '@agent-bundle/runtime'; import { - createProviderProcessLifetime, executeProviders, providerProcessLifetimeValue, type ExecutableProvider, + type ProviderProcessLifetime, } from '../routes/provider-execution.ts'; import { AgentTestError } from './errors.ts'; import type { AgentBundleTestManifest, TestableProviderDescriptor } from './manifest.ts'; @@ -23,13 +23,6 @@ import type { RenderedRouteProvenance } from './types.ts'; * the runtime's request contract reads it. */ -/** - * One process identity for this test worker, mirroring the generated scopes' - * module-scope `processLifetime`: `hits` counts every request the harness - * opened in this process, whichever proof level opened it. - */ -const processLifetime = createProviderProcessLifetime(); - export interface MountProvidersOptions { /** Explicit provider values from the test; when present they win and nothing is discovered. */ readonly explicit: AgentProviderValues | undefined; @@ -37,6 +30,16 @@ export interface MountProvidersOptions { readonly invocation: unknown; /** Absent for a module rendered directly: no project, so nothing to discover. */ readonly manifest: AgentBundleTestManifest | undefined; + /** + * The process identity of the simulated executable, scoped exactly as the + * artifact scopes its module-level `processLifetime`: one per CLI + * invocation (each generated executable starts at hit 1), one per rendered + * route request, and one per open in-memory MCP server session (shared by + * every request that session handles). Never shared across unrelated + * helper calls, so a provider branching on `hits` or `instanceId` cannot + * observe warmth the artifact would not exhibit. + */ + readonly processLifetime: ProviderProcessLifetime; readonly provenance?: RenderedRouteProvenance; readonly signal: AbortSignal; } @@ -63,10 +66,11 @@ const loadProvider = async ( /** * The `providers` value for one harness request scope: the explicit map when * the test supplied one, otherwise the project's conventional providers - * executed in the generated order over the framework-owned process identity. + * executed in the generated order over the caller's process identity. */ export const mountProviders = async (options: MountProvidersOptions): Promise => { if (options.explicit !== undefined) return options.explicit; + const { processLifetime } = options; processLifetime.hits += 1; if (options.manifest === undefined) { return { processLifetime: providerProcessLifetimeValue(processLifetime) }; diff --git a/packages/agent-bundle/src/test/render.ts b/packages/agent-bundle/src/test/render.ts index 2bd7bd99d..02186d3e9 100644 --- a/packages/agent-bundle/src/test/render.ts +++ b/packages/agent-bundle/src/test/render.ts @@ -26,6 +26,7 @@ import type { GeneratedCliRenderContext, GeneratedCliRenderSession, } from '../cli-entry.ts'; +import { createProviderProcessLifetime, type ProviderProcessLifetime } from '../routes/provider-execution.ts'; import type { CompiledCliCommand } from '../routes/types.ts'; import { AgentTestError, captured } from './errors.ts'; import { ROUTE_UNIT_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; @@ -628,6 +629,8 @@ export interface PrepareCliRenderHostOptions { readonly manifest: AgentBundleTestManifest; readonly modules: ReadonlyMap; readonly onValidated: (value: unknown) => void; + /** The invoking CLI's process identity; the rendered command runs inside that same simulated executable. */ + readonly processLifetime: ProviderProcessLifetime; readonly provenance: RenderedRouteProvenance; readonly signal: AbortSignal; } @@ -714,6 +717,7 @@ export const prepareCliRenderHost = async ( explicit: context.providers, invocation, manifest: options.manifest, + processLifetime: options.processLifetime, provenance: { ...options.provenance, routeId: command.routeId }, signal: request.signal, }); @@ -789,6 +793,9 @@ const prepareRender = async ( const collected: AgentProgressUpdate[] = []; const context = options.context ?? {}; const signal = options.signal ?? new AbortController().signal; + // A route-unit render stands in for one fresh executable serving one + // request; nothing is warm across renders, so each starts at hit 1. + const processLifetime = createProviderProcessLifetime(); const mounted = await mountManifestState(resolved.manifest, resolved.provenance, context, renderer, signal); const dispatcher = createFlightDispatcher({ collected, @@ -806,6 +813,7 @@ const prepareRender = async ( explicit: context.providers, invocation: request.invocation, manifest: resolved.manifest, + processLifetime, provenance: resolved.provenance, signal: request.signal, }), diff --git a/packages/agent-bundle/tests/projection/providers.test.ts b/packages/agent-bundle/tests/projection/providers.test.ts index 9540e29b0..11c8274a4 100644 --- a/packages/agent-bundle/tests/projection/providers.test.ts +++ b/packages/agent-bundle/tests/projection/providers.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from '@rstest/core'; import { cliJson, invokeCli } from '../../src/test/cli.ts'; import { AgentTestError } from '../../src/test/errors.ts'; -import { invokeMcpTool } from '../../src/test/mcp.ts'; +import { invokeMcpTool, openInMemoryMcpServer } from '../../src/test/mcp.ts'; import { renderRoute } from '../../src/test/render.ts'; import { testManifest } from '../../src/test/registry.ts'; @@ -35,7 +35,7 @@ describe('conventional providers through the harness', () => { expect(cliJson(run)).toEqual({ keys: ['libraryTooling', 'processLifetime'], libraryTooling: { kind: 'cli', surface: 'tooling inspect', tool: 'ffprobe 6.1' }, - processLifetime: { hits: expect.any(Number), instanceId: expect.any(String), pid: process.pid }, + processLifetime: { hits: 1, instanceId: expect.any(String), pid: process.pid }, }); }); @@ -57,6 +57,7 @@ describe('conventional providers through the harness', () => { expect(cliJson(run)).toEqual({ keys: ['libraryTooling', 'processLifetime'], libraryTooling: { kind: 'tool', surface: 'tool:harness/tooling', tool: 'ffprobe 6.1' }, + processLifetime: { hits: 1, instanceId: expect.any(String), pid: process.pid }, }); }); @@ -67,6 +68,7 @@ describe('conventional providers through the harness', () => { expect(call.structuredContent).toEqual({ keys: ['libraryTooling', 'processLifetime'], libraryTooling: { kind: 'tool', surface: 'tool:harness/tooling', tool: 'ffprobe 6.1' }, + processLifetime: { hits: 1, instanceId: expect.any(String), pid: process.pid }, }); }); @@ -76,6 +78,7 @@ describe('conventional providers through the harness', () => { expect(rendered.result).toEqual({ keys: ['libraryTooling', 'processLifetime'], libraryTooling: { kind: 'tool', surface: 'tool:harness/tooling', tool: 'ffprobe 6.1' }, + processLifetime: { hits: 1, instanceId: expect.any(String), pid: process.pid }, }); }); @@ -100,13 +103,47 @@ describe('conventional providers through the harness', () => { }); }); - it('counts every harness request in one process identity', async () => { - const first = cliJson(await invokeCli(['tooling', 'inspect'])) as { processLifetime: { hits: number; instanceId: string } }; - await renderRoute('tool:harness/tooling'); - const second = cliJson(await invokeCli(['tooling', 'inspect'])) as { processLifetime: { hits: number; instanceId: string } }; + it('gives every CLI invocation its own fresh process identity, like a separate generated executable', async () => { + type Lifetime = { processLifetime: { hits: number; instanceId: string; pid: number } }; + const first = cliJson(await invokeCli(['tooling', 'inspect'])) as Lifetime; + const second = cliJson(await invokeCli(['tooling', 'inspect'])) as Lifetime; - expect(second.processLifetime.instanceId).toBe(first.processLifetime.instanceId); - expect(second.processLifetime.hits).toBeGreaterThanOrEqual(first.processLifetime.hits + 2); + expect(first.processLifetime).toEqual({ hits: 1, instanceId: expect.any(String), pid: process.pid }); + expect(second.processLifetime).toEqual({ hits: 1, instanceId: expect.any(String), pid: process.pid }); + expect(second.processLifetime.instanceId).not.toBe(first.processLifetime.instanceId); + }); + + it('shares one process identity across the requests of one open in-memory MCP server only', async () => { + type Lifetime = { processLifetime: { hits: number; instanceId: string; pid: number } }; + const lifetimeOf = (result: unknown): Lifetime['processLifetime'] => + ((result as { structuredContent: Lifetime }).structuredContent).processLifetime; + + await using session = await openInMemoryMcpServer(); + const first = lifetimeOf(await session.client.callTool({ arguments: {}, name: 'tooling' })); + const second = lifetimeOf(await session.client.callTool({ arguments: {}, name: 'tooling' })); + await using other = await openInMemoryMcpServer(); + const elsewhere = lifetimeOf(await other.client.callTool({ arguments: {}, name: 'tooling' })); + const convenience = lifetimeOf(await invokeMcpTool('tooling')); + + // The same warm server serves both calls, exactly like the artifact's + // Flight worker; a second server, and the open-call-close convenience + // helper, are separate processes that start at hit 1. + expect(first).toEqual({ hits: 1, instanceId: expect.any(String), pid: process.pid }); + expect(second).toEqual({ hits: 2, instanceId: first.instanceId, pid: process.pid }); + expect(elsewhere).toEqual({ hits: 1, instanceId: expect.any(String), pid: process.pid }); + expect(elsewhere.instanceId).not.toBe(first.instanceId); + expect(convenience).toEqual({ hits: 1, instanceId: expect.any(String), pid: process.pid }); + expect(convenience.instanceId).not.toBe(first.instanceId); + }); + + it('gives every route-unit render a fresh process identity', async () => { + type Result = { processLifetime: { hits: number; instanceId: string } }; + const first = (await renderRoute('tool:harness/tooling')).result as Result; + const second = (await renderRoute('tool:harness/tooling')).result as Result; + + expect(first.processLifetime.hits).toBe(1); + expect(second.processLifetime.hits).toBe(1); + expect(second.processLifetime.instanceId).not.toBe(first.processLifetime.instanceId); }); it('uses an explicit context.providers map verbatim instead of discovering providers', async () => { From 8143cdae99065957799b3e6683e331538d1aa32f Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 08:46:54 +0000 Subject: [PATCH 09/13] fix(test): snapshot the process hit count before awaiting provider loaders Concurrent requests on one in-memory MCP server could each increment the shared lifetime before the first request reached executeProviders, so every request observed the final count. Capture each request's hit right after the increment, as the generated worker does, and hand the snapshot to the shared execution helper. --- packages/agent-bundle/src/test/providers.ts | 8 ++++++-- .../tests/projection/providers.test.ts | 16 ++++++++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/packages/agent-bundle/src/test/providers.ts b/packages/agent-bundle/src/test/providers.ts index 82a3df852..9c217cca9 100644 --- a/packages/agent-bundle/src/test/providers.ts +++ b/packages/agent-bundle/src/test/providers.ts @@ -72,8 +72,12 @@ export const mountProviders = async (options: MountProvidersOptions): Promise { expect(convenience.instanceId).not.toBe(first.instanceId); }); + it('hands concurrent requests on one server distinct hit counts, snapshotted before provider loading', async () => { + type Lifetime = { processLifetime: { hits: number; instanceId: string } }; + await using session = await openInMemoryMcpServer(); + + const results = await Promise.all( + Array.from({ length: 4 }, () => session.client.callTool({ arguments: {}, name: 'tooling' })), + ); + const lifetimes = results.map((result) => (result as { structuredContent: Lifetime }).structuredContent.processLifetime); + + // Like the generated worker, each request captures its own hit right after + // the increment; awaiting provider loaders must not let a concurrent + // request move it. + expect(lifetimes.map((lifetime) => lifetime.hits).sort((left, right) => left - right)).toEqual([1, 2, 3, 4]); + expect(new Set(lifetimes.map((lifetime) => lifetime.instanceId)).size).toBe(1); + }); + it('gives every route-unit render a fresh process identity', async () => { type Result = { processLifetime: { hits: number; instanceId: string } }; const first = (await renderRoute('tool:harness/tooling')).result as Result; From 3e086012479c0fd0fc4ee1d3943a0b8e1680dac7 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 09:23:15 +0000 Subject: [PATCH 10/13] fix(build,test): snapshot the process hit synchronously before state bindings Generated stateful scopes incremented processLifetime.hits, awaited state bindings, then snapshotted the value, so concurrent requests could observe the same count; the harness's in-memory server claimed its hit only after the bindings resolved. Both now claim and snapshot in one synchronous step before any await: the emitted scopes bind `processHit` at the increment, and the harness claims through claimProcessHit before requestBindings. The harness also looks up CLI command paths among authored commands only, since projected MCP commands carry their tool's route id and render through the tool branch. --- .../agent-bundle/src/build/entry-shell.ts | 20 ++++++-- .../src/routes/provider-execution.ts | 8 +++- packages/agent-bundle/src/test/cli.ts | 4 +- packages/agent-bundle/src/test/mcp.ts | 8 +++- packages/agent-bundle/src/test/providers.ts | 42 +++++++++------- packages/agent-bundle/src/test/render.ts | 13 +++-- .../agent-bundle/tests/entry-shell.test.ts | 12 +++-- .../tests/projection/providers.test.ts | 48 ++++++++++++++++++- 8 files changed, 119 insertions(+), 36 deletions(-) diff --git a/packages/agent-bundle/src/build/entry-shell.ts b/packages/agent-bundle/src/build/entry-shell.ts index 5ad3e58ba..428c8d5b2 100644 --- a/packages/agent-bundle/src/build/entry-shell.ts +++ b/packages/agent-bundle/src/build/entry-shell.ts @@ -293,7 +293,7 @@ export const generatedCliBinEntrySource = (options: GeneratedCliBinEntryOptions) " if (route === undefined || typeof route.module.default !== 'function') throw new TypeError('Generated CLI route must default-export an async function.');", ' const parsed = parseInput(route, input);', ' const cwd = process.cwd();', - ' processLifetime.hits += 1;', + ...processHitSource(' '), ...(options.state === undefined ? [] : [' const bindings = await runtimeState.requestBindings({ signal: context.signal });', ' try {']), @@ -412,7 +412,7 @@ export const generatedRenderedRouteWorkerSource = ( " if (route === undefined || typeof route.module.default !== 'function') throw new TypeError('Generated rendered route must default-export an async function component.');", ' const controller = new AbortController();', ' requests.set(message.id, controller);', - ' processLifetime.hits += 1;', + ...processHitSource(' '), ' try {', ' const cwd = process.cwd();', ...(options.state === undefined @@ -583,8 +583,18 @@ const providerRegistrySource = (providers: readonly CompiledProvider[]): readonl ? [] : ['const providers = Object.freeze([', ...providerRecords(providers), ']);']; -const processLifetimeValueSource = - '{ hits: processLifetime.hits, instanceId: processLifetime.instanceId, pid: processLifetime.pid }'; +/** + * Claims this request's hit on the process identity and snapshots it in the + * same synchronous step, before any state binding or provider `await`, so a + * concurrent request on the same scope cannot move the value this request + * mounts as `providers.processLifetime`. + */ +const processHitSource = (indent: string): readonly string[] => [ + `${indent}processLifetime.hits += 1;`, + `${indent}const processHit = { hits: processLifetime.hits, instanceId: processLifetime.instanceId, pid: processLifetime.pid };`, +]; + +const processLifetimeValueSource = 'processHit'; /** * Per-request provider execution shared by every generated request scope @@ -661,7 +671,7 @@ export const generatedRouteFlightWorkerSource = (options: GeneratedRouteFlightWo " if (route === undefined || typeof route.module.default !== 'function') throw new TypeError('Generated route must default-export an async Server Component.');", ' const controller = new AbortController();', ' requests.set(message.id, controller);', - ' processLifetime.hits += 1;', + ...processHitSource(' '), ' try {', ...(options.state === undefined ? [] diff --git a/packages/agent-bundle/src/routes/provider-execution.ts b/packages/agent-bundle/src/routes/provider-execution.ts index b43a01ded..fdaa34d74 100644 --- a/packages/agent-bundle/src/routes/provider-execution.ts +++ b/packages/agent-bundle/src/routes/provider-execution.ts @@ -41,9 +41,15 @@ export const createProviderProcessLifetime = (): ProviderProcessLifetime => ({ }); /** The immutable snapshot of one process lifetime a request observes. */ +export interface ProviderProcessLifetimeValue { + readonly hits: number; + readonly instanceId: string; + readonly pid: number; +} + export const providerProcessLifetimeValue = ( lifetime: ProviderProcessLifetime, -): { readonly hits: number; readonly instanceId: string; readonly pid: number } => ({ +): ProviderProcessLifetimeValue => ({ hits: lifetime.hits, instanceId: lifetime.instanceId, pid: lifetime.pid, diff --git a/packages/agent-bundle/src/test/cli.ts b/packages/agent-bundle/src/test/cli.ts index bbcb6f980..fc7a50bc6 100644 --- a/packages/agent-bundle/src/test/cli.ts +++ b/packages/agent-bundle/src/test/cli.ts @@ -25,7 +25,7 @@ import { createProviderProcessLifetime } from '../routes/provider-execution.ts'; import type { CompiledCliCommand } from '../routes/types.ts'; import { AgentTestError, captured } from './errors.ts'; import { CLI_DISPATCH_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; -import { mountProviders } from './providers.ts'; +import { claimProcessHit, mountProviders } from './providers.ts'; import { registeredRouteLoader, testManifest } from './registry.ts'; import { prepareCliRenderHost, type HarnessOptionsArguments, type RenderRouteContextInit } from './render.ts'; import type { AgentRouteModule, RenderedRouteProvenance } from './types.ts'; @@ -239,7 +239,7 @@ export const invokeCli = async ( explicit: context.providers, invocation: { kind: 'cli', props: { args: execution.args, command: commandPath(command) } }, manifest, - processLifetime, + processHit: claimProcessHit(processLifetime), provenance: { ...provenance, kind: 'cli', routeId: command.routeId, source: 'manifest', targets: [] }, signal: execution.signal, }); diff --git a/packages/agent-bundle/src/test/mcp.ts b/packages/agent-bundle/src/test/mcp.ts index 7184373d7..4938f3a26 100644 --- a/packages/agent-bundle/src/test/mcp.ts +++ b/packages/agent-bundle/src/test/mcp.ts @@ -25,7 +25,7 @@ import type { createGeneratedRuntimeState } from '@agent-bundle/runtime/mount'; import { createProviderProcessLifetime } from '../routes/provider-execution.ts'; import { AgentTestError, captured } from './errors.ts'; import { MCP_IN_MEMORY_PROOF_LEVEL, type AgentBundleTestManifest } from './manifest.ts'; -import { mountProviders } from './providers.ts'; +import { claimProcessHit, mountProviders } from './providers.ts'; import { registeredRouteLoader, testManifest } from './registry.ts'; import type { HarnessOptionsArguments, RenderRouteContextInit } from './render.ts'; import type { RenderedRouteProvenance, TestableRouteDescriptor } from './types.ts'; @@ -333,6 +333,10 @@ export const openInMemoryMcpServer = async < details: [`registered: ${Object.keys(routes).sort().join(', ')}`], }); } + // The hit is claimed before state bindings are awaited, in the + // generated worker's order, so a failed or slow binding still consumes + // this request's hit and concurrent requests keep arrival order. + const processHit = claimProcessHit(processLifetime); const bindings = await runtimeState?.requestBindings({ signal: request.signal }); try { // Conventional providers run before the scope opens, over the same @@ -342,7 +346,7 @@ export const openInMemoryMcpServer = async < explicit: context.providers, invocation: request.invocation, manifest, - processLifetime, + processHit, ...(descriptor === undefined ? {} : { provenance: routeProvenance(descriptor, manifest) }), signal: request.signal, }); diff --git a/packages/agent-bundle/src/test/providers.ts b/packages/agent-bundle/src/test/providers.ts index 9c217cca9..08c9d93ef 100644 --- a/packages/agent-bundle/src/test/providers.ts +++ b/packages/agent-bundle/src/test/providers.ts @@ -5,6 +5,7 @@ import { providerProcessLifetimeValue, type ExecutableProvider, type ProviderProcessLifetime, + type ProviderProcessLifetimeValue, } from '../routes/provider-execution.ts'; import { AgentTestError } from './errors.ts'; import type { AgentBundleTestManifest, TestableProviderDescriptor } from './manifest.ts'; @@ -31,15 +32,10 @@ export interface MountProvidersOptions { /** Absent for a module rendered directly: no project, so nothing to discover. */ readonly manifest: AgentBundleTestManifest | undefined; /** - * The process identity of the simulated executable, scoped exactly as the - * artifact scopes its module-level `processLifetime`: one per CLI - * invocation (each generated executable starts at hit 1), one per rendered - * route request, and one per open in-memory MCP server session (shared by - * every request that session handles). Never shared across unrelated - * helper calls, so a provider branching on `hits` or `instanceId` cannot - * observe warmth the artifact would not exhibit. + * This request's claimed hit on the simulated executable's process identity + * (see {@link claimProcessHit}); mounted verbatim as `providers.processLifetime`. */ - readonly processLifetime: ProviderProcessLifetime; + readonly processHit: ProviderProcessLifetimeValue; readonly provenance?: RenderedRouteProvenance; readonly signal: AbortSignal; } @@ -63,21 +59,33 @@ const loadProvider = async ( return { key: descriptor.key, module: await loader(), source: descriptor.relativePath }; }; +/** + * Claims one request's hit on a simulated executable's process identity and + * snapshots it in the same synchronous step, exactly where the generated + * scopes do: before any state binding or provider module `await`, so a + * concurrent request on the same identity cannot move this request's value. + * + * Callers scope the identity as the artifact scopes its module-level + * `processLifetime`: one per CLI invocation (each generated executable starts + * at hit 1), one per rendered route request, and one per open in-memory MCP + * server session (shared by every request that session handles). It is never + * shared across unrelated helper calls, so a provider branching on `hits` or + * `instanceId` cannot observe warmth the artifact would not exhibit. + */ +export const claimProcessHit = (processLifetime: ProviderProcessLifetime): ProviderProcessLifetimeValue => { + processLifetime.hits += 1; + return providerProcessLifetimeValue(processLifetime); +}; + /** * The `providers` value for one harness request scope: the explicit map when * the test supplied one, otherwise the project's conventional providers - * executed in the generated order over the caller's process identity. + * executed in the generated order over the claimed process hit. */ export const mountProviders = async (options: MountProvidersOptions): Promise => { if (options.explicit !== undefined) return options.explicit; - const { processLifetime } = options; - processLifetime.hits += 1; - // Snapshot before the first await, as the generated worker does right after - // its increment: a concurrent request on the same lifetime must not move - // this request's hit count while its provider modules load. - const snapshot = providerProcessLifetimeValue(processLifetime); if (options.manifest === undefined) { - return { processLifetime: snapshot }; + return { processLifetime: options.processHit }; } const providers: ExecutableProvider[] = []; for (const descriptor of options.manifest.providers ?? []) { @@ -85,7 +93,7 @@ export const mountProviders = async (options: MountProvidersOptions): Promise candidate.routeId === routeId); + // Only authored `src/cli/**` commands have a `cli` route kind. Projected + // MCP commands (`command.mcp`) carry their tool's route id, so a request + // for one resolves as that `tool` route above, exactly like the generated + // entry's `command.mcp !== undefined` branch. + const command = manifest?.cliCommands.find((candidate) => + candidate.mcp === undefined && candidate.routeId === routeId); if (command !== undefined) return command.path.join(' '); return (routeId.startsWith('cli:') ? routeId.slice('cli:'.length) : routeId).replaceAll('/', ' '); } @@ -717,7 +722,7 @@ export const prepareCliRenderHost = async ( explicit: context.providers, invocation, manifest: options.manifest, - processLifetime: options.processLifetime, + processHit: claimProcessHit(options.processLifetime), provenance: { ...options.provenance, routeId: command.routeId }, signal: request.signal, }); @@ -813,7 +818,7 @@ const prepareRender = async ( explicit: context.providers, invocation: request.invocation, manifest: resolved.manifest, - processLifetime, + processHit: claimProcessHit(processLifetime), provenance: resolved.provenance, signal: request.signal, }), diff --git a/packages/agent-bundle/tests/entry-shell.test.ts b/packages/agent-bundle/tests/entry-shell.test.ts index 16f4e3c10..9e792d65e 100644 --- a/packages/agent-bundle/tests/entry-shell.test.ts +++ b/packages/agent-bundle/tests/entry-shell.test.ts @@ -364,7 +364,7 @@ it('generates the warm react-server Flight worker separately from the MCP dispat '"hook:event-route:tool-after": Object.freeze({ event: "tool/after", id: "event:tool/after", kind: \'event-route\'', ); expect(createHash('sha256').update(source).digest('hex')).toBe( - 'f0a574cc26aa4c7d5556e7468d13743c1da55d372fe5e6eae9151df0be873948', + '36f042498df1933c6321bd21e4585599a0d39e5ddb3890657bd660c322f4cc23', ); expect(generate({ artifactEpoch: 'route-fixture@1.2.3', @@ -571,6 +571,12 @@ it('mounts deterministic per-request providers for plain routed CLI commands (#3 expect(withProviders.indexOf('for (const provider of providers)')).toBeLessThan( withProviders.indexOf('const result = await runAgentRequest({'), ); + // The request's hit is claimed and snapshotted in one synchronous step + // before any await, so concurrent requests cannot move each other's value. + expect(withProviders).toContain( + 'processLifetime.hits += 1;\n const processHit = { hits: processLifetime.hits, instanceId: processLifetime.instanceId, pid: processLifetime.pid };', + ); + expect(withProviders).toContain('const providerValues = { processLifetime: processHit };'); // A project without providers still mounts only the framework-owned process identity. const withoutProviders = entryShellModule.generatedCliBinEntrySource({ @@ -579,9 +585,7 @@ it('mounts deterministic per-request providers for plain routed CLI commands (#3 routes: [route], }); expect(withoutProviders).not.toContain('const providers = Object.freeze(['); - expect(withoutProviders).toContain( - 'providers: { processLifetime: { hits: processLifetime.hits, instanceId: processLifetime.instanceId, pid: processLifetime.pid } },', - ); + expect(withoutProviders).toContain('providers: { processLifetime: processHit },'); expect(withoutProviders).not.toContain('import * as provider0'); }); diff --git a/packages/agent-bundle/tests/projection/providers.test.ts b/packages/agent-bundle/tests/projection/providers.test.ts index 114673b07..17dbb7b03 100644 --- a/packages/agent-bundle/tests/projection/providers.test.ts +++ b/packages/agent-bundle/tests/projection/providers.test.ts @@ -1,4 +1,8 @@ +import { setTimeout as sleep } from 'node:timers/promises'; + import { describe, expect, it } from '@rstest/core'; +import { createMemoryStateDriver, defineState, type AgentStateDriver } from '@agent-bundle/runtime/state'; +import { z } from 'zod'; import { cliJson, invokeCli } from '../../src/test/cli.ts'; import { AgentTestError } from '../../src/test/errors.ts'; @@ -72,7 +76,11 @@ describe('conventional providers through the harness', () => { }); }); - it('mounts providers for an MCP route at the route-unit level', async () => { + it('mounts providers for an MCP route at the route-unit level, including when it is also a projected CLI command', async () => { + // `harness tooling` is projected onto the CLI from this tool; its command + // carries the tool's route id, so rendering it takes the tool branch the + // generated entry takes for `command.mcp !== undefined`. + expect(testManifest().cliCommands.find((command) => command.mcp?.tool === 'tooling')?.routeId).toBe('tool:harness/tooling'); const rendered = await renderRoute('tool:harness/tooling'); expect(rendered.result).toEqual({ @@ -152,6 +160,44 @@ describe('conventional providers through the harness', () => { expect(new Set(lifetimes.map((lifetime) => lifetime.instanceId)).size).toBe(1); }); + it('claims the hit before awaiting state bindings, so hits follow arrival order like the generated worker', async () => { + type Lifetime = { processLifetime: { hits: number; instanceId: string } }; + const definition = defineState({ + events: { changed: z.object({ value: z.string() }).strict() }, + id: 'providers/request-state', + initial: { value: '' }, + lifetime: 'request', + reduce: (_state, event) => ({ value: event.payload.value }), + schema: z.object({ value: z.string() }).strict(), + }); + const inner = createMemoryStateDriver({ lifetime: 'request' }); + let projectOpens = 0; + const driver: AgentStateDriver = { + ...inner, + open: async (opened) => { + // Only the first request's project store is slow to open; the second + // request's bindings resolve first. + if (opened.id === definition.id && projectOpens++ === 0) await sleep(150); + return inner.open(opened); + }, + }; + await using session = await openInMemoryMcpServer({ state: { definition, driver } }); + + const [first, second] = await Promise.all([ + session.client.callTool({ arguments: {}, name: 'tooling' }), + session.client.callTool({ arguments: {}, name: 'tooling' }), + ]); + const lifetimeOf = (result: unknown): Lifetime['processLifetime'] => + (result as { structuredContent: Lifetime }).structuredContent.processLifetime; + + // The generated worker increments and snapshots before `requestBindings`; + // the request that arrived first keeps hit 1 even though its state + // bindings resolved last. + expect(lifetimeOf(first).hits).toBe(1); + expect(lifetimeOf(second).hits).toBe(2); + expect(projectOpens).toBe(2); + }); + it('gives every route-unit render a fresh process identity', async () => { type Result = { processLifetime: { hits: number; instanceId: string } }; const first = (await renderRoute('tool:harness/tooling')).result as Result; From a366054d54461de1c47852df346350fc6b472cfc Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 09:48:37 +0000 Subject: [PATCH 11/13] fix(test): keep harness context optional under provider typegen and document module-evaluation scope Auto-mounting made #409's harness rule unreachable: once the generated augmentation declared provider keys, HarnessOptionsArguments and RenderRouteContextInit turned `options`/`context.providers` mandatory, so a typed project could never let the harness mount its real providers. The harness now keeps both optional (an explicit map must still carry every declared key; a direct runAgentRequest still requires providers) and framework-mode.md, entry-conventions.md, and the README describe the auto-mount contract instead of "the harness never executes provider modules". They also record what the harness does not simulate: provider modules are evaluated once per test worker, so module-level provider state is shared across simulated executables and is only proven cold by the proof levels that spawn the artifact. --- .../test-harness-conventional-providers.md | 2 +- docs/entry-conventions.md | 8 ++++- docs/framework-mode.md | 20 +++++++---- packages/agent-bundle/README.md | 17 +++++++++ packages/agent-bundle/src/test/cli.ts | 5 +-- packages/agent-bundle/src/test/mcp.ts | 5 +-- packages/agent-bundle/src/test/providers.ts | 12 +++++++ packages/agent-bundle/src/test/render.ts | 35 ++++++++++--------- 8 files changed, 74 insertions(+), 30 deletions(-) diff --git a/.changeset/test-harness-conventional-providers.md b/.changeset/test-harness-conventional-providers.md index f145a157e..656d4773d 100644 --- a/.changeset/test-harness-conventional-providers.md +++ b/.changeset/test-harness-conventional-providers.md @@ -2,4 +2,4 @@ "agent-bundle": patch --- -The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity scoped like the artifact's (fresh per CLI invocation and per route-unit render; shared across the requests of one open in-memory MCP server). Passing `context.providers` opts out and mounts the explicit map verbatim. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id, and the generated Flight worker now mounts an event route's compiled id (`event:tool/after`) as `invocation.operationId`, matching the hook shell's request scope, the lifecycle replay, and the harness instead of the internal hook identity. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. +The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity scoped like the artifact's (fresh per CLI invocation and per route-unit render; shared across the requests of one open in-memory MCP server). Passing `context.providers` opts out and mounts the explicit map verbatim. Because the harness now supplies providers itself, its `options` argument and `context.providers` stay optional even once the generated `.agent-bundle/routes.d.ts` augmentation declares provider keys (`HarnessOptionsArguments` and `RenderRouteContextInit` no longer turn mandatory); an explicit map must still carry every declared key, and a direct `runAgentRequest` still requires `providers`. The harness reproduces the per-executable process identity, not per-executable module evaluation: provider modules are evaluated once per test worker, so module-level provider state is shared across the simulated executables of one worker and is only proven cold by the proof levels that spawn the artifact. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id, and the generated Flight worker now mounts an event route's compiled id (`event:tool/after`) as `invocation.operationId`, matching the hook shell's request scope, the lifecycle replay, and the harness instead of the internal hook identity. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. diff --git a/docs/entry-conventions.md b/docs/entry-conventions.md index 9c5b352b0..d74623e92 100644 --- a/docs/entry-conventions.md +++ b/docs/entry-conventions.md @@ -186,7 +186,13 @@ has no project to discover, so it observes only `processLifetime`. Once the generated `.agent-bundle/routes.d.ts` augmentation declares provider keys, an explicit `context.providers` map must carry every declared key (as must `providers` on a direct `runAgentRequest`), so a fixture that omits a value the -route's types promise is a compile error rather than a runtime `undefined`. +route's types promise is a compile error rather than a runtime `undefined`; +omitting `context.providers` altogether stays legal and mounts the real +providers. The harness reproduces the per-executable process identity, not +per-executable module evaluation: provider modules are evaluated once per test +worker, so module-level provider state is shared across the simulated +executables of that worker and is only proven cold by the proof levels that +spawn the artifact. ### Handler request context diff --git a/docs/framework-mode.md b/docs/framework-mode.md index caa0de9de..adcbf68d9 100644 --- a/docs/framework-mode.md +++ b/docs/framework-mode.md @@ -136,13 +136,19 @@ and augments `@agent-bundle/runtime`'s `AgentProviderValues`, so `(await agent()).providers.library` is a `LibraryContext` with no cast once the file is part of the project's TypeScript program (add `".agent-bundle/routes.d.ts"` to `tsconfig.json` `include`). Undeclared keys -stay `unknown`. Route-unit and CLI-dispatch tests inject fixture values through -`renderRoute(id, { context: { providers: { library } } })`; the harness never -executes provider modules on a test's behalf. Because the augmentation makes -declared keys required, the same program also requires `context.providers` -(and the harness `options` argument) on every `renderRoute`, `invokeCli`, and -in-memory MCP call, and `providers` on a direct `runAgentRequest`: a handler -typed against `providers.library` can never observe an unchecked `undefined`. +stay `unknown`. The `agent-bundle/test` harness (`renderRoute`, `invokeCli`, +the in-memory MCP helpers) mounts the project's providers automatically, in the +same order and with the same fail-closed semantics as the generated request +scopes, so a route-unit test observes what the artifact would mount — including +a provider that reaches the network or the file system. To stub one, inject +fixture values through `renderRoute(id, { context: { providers: { library } } })`: +an explicit map is mounted verbatim and no provider module executes. Because +the augmentation makes declared keys required, an explicit `context.providers` +must carry every declared key, and a direct `runAgentRequest` (where nothing +else supplies providers) requires `providers` outright: a handler typed against +`providers.library` can never observe an unchecked `undefined`. See the +[harness section](../packages/agent-bundle/README.md#testing-routes) for the +module-evaluation caveat that applies to provider-level state. ### What reaches the MCP wire diff --git a/packages/agent-bundle/README.md b/packages/agent-bundle/README.md index 46421d84e..a55377789 100644 --- a/packages/agent-bundle/README.md +++ b/packages/agent-bundle/README.md @@ -436,6 +436,23 @@ const stubbed = await invokeCli(['library', 'audit', './books'], { }); ``` +`context` (and `context.providers`) stays optional even once the generated +`.agent-bundle/routes.d.ts` augmentation declares provider keys: omitting it +runs the real providers, which is what the artifact does, while an explicit map +must carry every declared key, so a fixture cannot leave a promised value +`undefined`. Only a direct `runAgentRequest` requires `providers` in that case, +because nothing else would supply them. + +The harness simulates the process identity per executable, not module +evaluation: one Rstest worker evaluates each provider module once, so +module-level state in a provider is shared across every simulated CLI +invocation, render, and in-memory server in that worker (as it is for the route +modules themselves), whereas a real artifact evaluates the module afresh in +every CLI process and Flight worker. A provider's module-level cache, counter, +or singleton is therefore only proven by the packed and projected proof levels +that spawn the artifact; a route-unit test that needs cold state should stub +the provider through `context.providers` or reset that state between calls. + Matchers over the Agent Document contracts: `toHaveStatus`, `toContainMarkdown`, `toContainText`, `toHaveValue`, `toHaveError`, and `toHaveNodeKinds`. diff --git a/packages/agent-bundle/src/test/cli.ts b/packages/agent-bundle/src/test/cli.ts index fc7a50bc6..b7bbe39f7 100644 --- a/packages/agent-bundle/src/test/cli.ts +++ b/packages/agent-bundle/src/test/cli.ts @@ -44,8 +44,9 @@ export interface InvokeCliOptionsBase { /** * Dispatch options; `context` carries the request-scope overrides for the - * dispatched command over the runtime's request contract and is required once - * the project declares providers (see {@link RenderRouteContextInit}). + * dispatched command over the runtime's request contract; omitting it (or its + * `providers`) mounts the project's conventional providers exactly as the + * generated executable does (see {@link RenderRouteContextInit}). */ export type InvokeCliOptions = InvokeCliOptionsBase & RenderRouteContextInit; diff --git a/packages/agent-bundle/src/test/mcp.ts b/packages/agent-bundle/src/test/mcp.ts index 4938f3a26..ad31b76c5 100644 --- a/packages/agent-bundle/src/test/mcp.ts +++ b/packages/agent-bundle/src/test/mcp.ts @@ -75,8 +75,9 @@ export interface InMemoryMcpSessionOptionsBase< /** * Session options; `context` holds the request-scoped overrides applied to - * every route render in this session and is required once the project - * declares providers (see {@link RenderRouteContextInit}). + * every route render in this session; omitting it (or its `providers`) mounts + * the project's conventional providers exactly as the generated server does + * (see {@link RenderRouteContextInit}). */ export type InMemoryMcpSessionOptions< TState = unknown, diff --git a/packages/agent-bundle/src/test/providers.ts b/packages/agent-bundle/src/test/providers.ts index 08c9d93ef..028c4e94e 100644 --- a/packages/agent-bundle/src/test/providers.ts +++ b/packages/agent-bundle/src/test/providers.ts @@ -22,6 +22,18 @@ import type { RenderedRouteProvenance } from './types.ts'; * observes the provider map the artifact would mount. A test that passes * `context.providers` opts out: the explicit map is used verbatim, exactly as * the runtime's request contract reads it. + * + * What the harness simulates per executable is the framework-owned process + * identity (`processLifetime`), not module evaluation. Provider modules load + * through the generated setup's static loaders, so one Rstest worker evaluates + * each module once and every simulated CLI invocation, route render, and + * in-memory server in that worker shares its module-level state — the same + * way the worker shares the route modules themselves. A real artifact + * evaluates the module afresh in every CLI process and Flight worker, so a + * provider's module-level cache, counter, or singleton is only proven by the + * packed and projected proof levels that spawn the artifact; a route-unit test + * that needs cold module state should substitute a fixture through + * `context.providers` or reset that state between calls. */ export interface MountProvidersOptions { diff --git a/packages/agent-bundle/src/test/render.ts b/packages/agent-bundle/src/test/render.ts index 459a28606..0d838b771 100644 --- a/packages/agent-bundle/src/test/render.ts +++ b/packages/agent-bundle/src/test/render.ts @@ -52,24 +52,27 @@ import type { * `@agent-bundle/runtime`. `providers` is the opt-out for conventional * provider discovery: when present it is mounted verbatim; when absent the * harness executes the project's `src/providers/*` exactly as the generated - * request scopes do. + * request scopes do. It stays optional even once the generated + * `.agent-bundle/routes.d.ts` augmentation declares provider keys — omitting + * it runs the real providers, which is the artifact's behavior — while an + * explicit map must still carry every declared key, so a fixture cannot leave + * a promised value `undefined`. */ -export type RenderRouteContext = Omit & { +export type RenderRouteContext = Omit & { readonly invocation?: Omit; readonly progress?: AgentProgressReporter; + readonly providers?: AgentProviderValues; }; /** - * The `context` member of every harness call. The harness installs fixture - * values instead of executing `src/providers/*`, so once the project's - * generated `.agent-bundle/routes.d.ts` augmentation declares required provider - * keys, `context` (and its `providers`) becomes mandatory: a test cannot omit - * the fixtures while the route's types promise them. Provider-free projects - * keep `context` optional. + * The `context` member of every harness call. Unlike a direct + * `runAgentRequest`, where `providers` becomes mandatory once the augmentation + * declares keys because nothing else would supply them, a harness call + * mounts the project's conventional providers itself, so `context` is always + * optional: omitting it observes what the artifact mounts, and passing + * `context.providers` substitutes a complete fixture map. */ -export type RenderRouteContextInit = Record extends AgentProviderValues - ? { readonly context?: RenderRouteContext } - : { readonly context: RenderRouteContext }; +export type RenderRouteContextInit = { readonly context?: RenderRouteContext }; export interface RenderRouteOptionsBase { /** CLI route arguments; `cli` routes only. */ @@ -89,13 +92,11 @@ export interface RenderRouteOptionsBase { export type RenderRouteOptions = RenderRouteOptionsBase & RenderRouteContextInit; /** - * The trailing options parameter of every harness entry point. Provider-free - * projects may omit it; once the generated augmentation declares provider - * keys it is mandatory, so no harness call can silently skip the fixtures. + * The trailing options parameter of every harness entry point. It is always + * optional: a call that omits it mounts the project's conventional providers + * exactly as the generated request scopes do (see {@link RenderRouteContextInit}). */ -export type HarnessOptionsArguments = Record extends AgentProviderValues - ? readonly [options?: Options] - : readonly [options: Options]; +export type HarnessOptionsArguments = readonly [options?: Options]; export interface RenderedRoute { /** The final Agent Document the real renderer produced. */ From 34b02306128cfcf601cb3f636ca7405dd183f9b2 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 10:16:19 +0000 Subject: [PATCH 12/13] test(typegen): pin that harness calls stay legal without context under provider typegen The #409 acceptance pinned `renderRoute(id)` as a compile error once the augmentation declares provider keys. With the harness mounting the project's providers itself that call is the artifact-faithful one, so it now typechecks clean alongside a call that passes only `input`, while a partial explicit fixture still fails on the missing key and a direct runAgentRequest still requires `providers`. --- .../agent-bundle/tests/provider-typegen.test.ts | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/packages/agent-bundle/tests/provider-typegen.test.ts b/packages/agent-bundle/tests/provider-typegen.test.ts index 34dc11abb..cbb4264c3 100644 --- a/packages/agent-bundle/tests/provider-typegen.test.ts +++ b/packages/agent-bundle/tests/provider-typegen.test.ts @@ -113,9 +113,11 @@ it('types (await agent()).providers. from the generated provider declaratio 'export const wrong = async (): Promise => (await agent()).providers.library;', '', ].join('\n')), - // Contexts that do not run src/providers/* — a custom runAgentRequest host - // or a route-unit fixture — must supply the declared keys, or the handler's - // typed `providers.library` would dereference undefined at runtime. + // A custom runAgentRequest host runs no src/providers/*, so it must supply + // the declared keys, or the handler's typed `providers.library` would + // dereference undefined at runtime. The harness mounts the project's + // providers itself, so a call without `context` is legal and observes the + // real values; an explicit `context.providers` fixture must be complete. writeProjectFile(root, 'custom-scope.ts', [ "import { runAgentRequest } from '@agent-bundle/runtime';", "import { renderRoute } from 'agent-bundle/test';", @@ -125,6 +127,8 @@ it('types (await agent()).providers. from the generated provider declaratio 'export const complete = async (): Promise => {', " await runAgentRequest({ invocation: { kind: 'tool' }, providers: { buildNumber: 7, library } }, async () => undefined);", " await renderRoute('tool:curator/status', { context: { providers: { buildNumber: 7, library } } });", + " await renderRoute('tool:curator/status');", + " await renderRoute('tool:curator/status', { input: {} });", '};', '', ].join('\n')), @@ -138,7 +142,6 @@ it('types (await agent()).providers. from the generated provider declaratio "import type { LibraryContext } from './src/providers/library.js';", "const library: LibraryContext = { stages: ['discover'], surface: 'tool' };", "export const partial = renderRoute('tool:curator/status', { context: { providers: { library } } });", - "export const absent = renderRoute('tool:curator/status');", '', ].join('\n')), ]); @@ -160,7 +163,6 @@ it('types (await agent()).providers. from the generated provider declaratio expect(missingProviders).toHaveLength(1); expect(missingProviders[0]).toContain("Property 'providers' is missing"); const missingFixture = typecheck(root, 'missing-fixture.ts'); - expect(missingFixture).toHaveLength(2); + expect(missingFixture).toHaveLength(1); expect(missingFixture[0]).toContain("Property '\"buildNumber\"' is missing"); - expect(missingFixture[1]).toContain('Expected 2 arguments, but got 1.'); }); From 7887b1369f9e35fb8a383cdfe45532f8ef984ab6 Mon Sep 17 00:00:00 2001 From: ScriptedAlchemy Date: Thu, 3 Sep 2026 10:22:23 +0000 Subject: [PATCH 13/13] fix(test,changeset): scale the watcher e2e outer timeouts and rewrite the changeset as a release summary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The three examples-real tests that wait on watcher rebuilds bounded their rebuild waits at 60s × timeScale but kept fixed 120s/150s outer timeouts, so in CI (timeScale 4) Rstest could end the test before its own readiness wait did. Their outer timeouts scale the same way now. The changeset is rewritten per AGENTS.md as an imperative user-facing summary naming the harness exports and the harness error, ending with the PR reference. --- .changeset/test-harness-conventional-providers.md | 2 +- packages/workbench/tests/examples-real.e2e.test.ts | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.changeset/test-harness-conventional-providers.md b/.changeset/test-harness-conventional-providers.md index 656d4773d..956027f31 100644 --- a/.changeset/test-harness-conventional-providers.md +++ b/.changeset/test-harness-conventional-providers.md @@ -2,4 +2,4 @@ "agent-bundle": patch --- -The `agent-bundle/test` harness now mounts conventional request context providers (`src/providers/*`) for every manifest-backed request scope — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), and the in-memory MCP helpers — exactly as the generated entries do: discovered from the compiled manifest, executed once per request in the same deterministic key order with the same surface-specific `invocation`, fail-closed with the same messages, and seeded with a `processLifetime` process identity scoped like the artifact's (fresh per CLI invocation and per route-unit render; shared across the requests of one open in-memory MCP server). Passing `context.providers` opts out and mounts the explicit map verbatim. Because the harness now supplies providers itself, its `options` argument and `context.providers` stay optional even once the generated `.agent-bundle/routes.d.ts` augmentation declares provider keys (`HarnessOptionsArguments` and `RenderRouteContextInit` no longer turn mandatory); an explicit map must still carry every declared key, and a direct `runAgentRequest` still requires `providers`. The harness reproduces the per-executable process identity, not per-executable module evaluation: provider modules are evaluated once per test worker, so module-level provider state is shared across the simulated executables of one worker and is only proven cold by the proof levels that spawn the artifact. `renderRoute` now hands providers and the request scope the executable surface the artifact records — a routed CLI command's space-joined command path and a script's path-derived name — instead of the route id, and the generated Flight worker now mounts an event route's compiled id (`event:tool/after`) as `invocation.operationId`, matching the hook shell's request scope, the lifecycle replay, and the harness instead of the internal hook identity. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and the provider execution contract shared by the generated scopes and the harness lives in one module. +Mount conventional request context providers (`src/providers/*`) in the `agent-bundle/test` harness for every manifest-backed call — `renderRoute`, `renderRouteEvents`, `invokeCli` (plain, rendered, and projected MCP commands), `openInMemoryMcpServer`, and `invokeMcpTool` — exactly as the generated request scopes do: same deterministic key order, same surface-specific `invocation`, same fail-closed factory errors, and a `providers.processLifetime` scoped like the artifact's (fresh per `invokeCli` call and per `renderRoute` render, shared across one open in-memory MCP session). Pass `context.providers` to mount an explicit fixture map instead; `context` and its `providers` stay optional even once the generated `.agent-bundle/routes.d.ts` augmentation declares provider keys (`HarnessOptionsArguments`, `RenderRouteContextInit`), while an explicit map must carry every declared key and a direct `runAgentRequest` still requires `providers`. Provider modules are evaluated once per test worker, so module-level provider state is shared across simulated executables; prove cold state through the proof levels that spawn the artifact. Hand `renderRoute` providers and the request scope the executable surface the artifact records (a routed CLI command's space-joined path, a script's path-derived name) instead of the route id, and mount an event route's compiled id (`event:tool/after`) as `invocation.operationId` in the generated Flight worker, matching the hook shell, lifecycle replay, and harness. The test manifest gains `providers`, the generated Rstest setup registers provider loaders (test registry version 4), and a project whose setup predates that registration fails with the `manifest-unavailable` harness error naming the provider. (#399) diff --git a/packages/workbench/tests/examples-real.e2e.test.ts b/packages/workbench/tests/examples-real.e2e.test.ts index ce122f0b9..866bacfef 100644 --- a/packages/workbench/tests/examples-real.e2e.test.ts +++ b/packages/workbench/tests/examples-real.e2e.test.ts @@ -120,7 +120,7 @@ e2e('drives the populated Skills Starter in real Chrome', { timeout: 90_000 }, a } }); -e2e('reveals, retains, repairs, and removes capabilities without reloading Chrome', { timeout: 120_000 }, async ({ page }) => { +e2e('reveals, retains, repairs, and removes capabilities without reloading Chrome', { timeout: 120_000 * timeScale }, async ({ page }) => { await buildWorkbench(); const project = await copyExample('skills-starter'); const configPath = join(project.root, 'agent-bundle.config.ts'); @@ -185,7 +185,7 @@ e2e('reveals, retains, repairs, and removes capabilities without reloading Chrom } }); -e2e('drives Hooks, scripts, logs, diagnostics, and repair in real Chrome', { timeout: 150_000 }, async ({ page }) => { +e2e('drives Hooks, scripts, logs, diagnostics, and repair in real Chrome', { timeout: 150_000 * timeScale }, async ({ page }) => { await buildWorkbench(); const project = await copyExample('hooks-and-scripts'); const hookSource = join(project.root, 'src', 'hooks', 'session-start.ts'); @@ -572,7 +572,7 @@ e2e('drives every populated MCP App workflow surface in real Chrome', { timeout: } }); -e2e('renders the flagship compiled route catalog by server and kind in real Chrome', { timeout: 150_000 }, async ({ page }) => { +e2e('renders the flagship compiled route catalog by server and kind in real Chrome', { timeout: 150_000 * timeScale }, async ({ page }) => { await buildWorkbench(); const project = await copyExample('audiobook-curator'); const conversionSource = join(project.root, 'src', 'conversion.ts');